Flask之Hello world 详解

**Flask之Hello world 详解

========================**

以下讲解假设你对python有基本了解,熟悉wsgi,以及了解某种python web framework.

复制代码
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return "HELLO WROLD"

if __name__ == '__main__':
    app.run(debug=True)
  1. Flask的实例app就是我们的WSGI application.
  2. 创建Flask实例需要指定一个参数,这个参数一般是application的模块名字或者是包名.Flask根据这个参数定位templates,static files等.
  3. route装饰器告诉Flask什么样的请求路径对应这个函数

####Routing

route()装饰器支持变量规则,用<variable_name>表示.还可以制订一个转换器.例如:

复制代码
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

@app.route('/user/<path:location>')
def show_path(location):
    return location

有三种转换器:

复制代码
int	    accepts integers
float	like int but for floating point values
path	like the default but also accepts slashes

####HTTP METHOD

复制代码
from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == "POST":
        return 'post'
    else:
        return 'get'

####Static Files

在package或则module同目录下创建static目录

复制代码
url_for('static', filename='style.css')

####rendering templates

默认Flask配置JinJia2作为模板引擎,因为他们是一家的.Flask会在templates目录下查找模板文件,如果application是一个module,那么这个templates目录与application同级目录.如果他是一个package:

  • case 1: a module:

    /application.py

    /templates

    /hello.html

  • case 2: a application

    /application

    /init .py

    /templates

    /hello.html

渲染模板使用render_template()

复制代码
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html',name=name)

JinJia2 模板的语法和Mako以及django的语法都差不多,可以稍作了解

复制代码
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello World!</h1>
{% endif %}

####Context locals

先跳过

相关推荐
jerryinwuhan3 分钟前
pybullet入门到入门_1
开发语言·人工智能·python
景彡先生22 分钟前
Python列表(List)完全指南:从入门到实战优化
windows·python·list
花开花富贵34 分钟前
是谁不会表达?来看看程序员的浪漫❤ 1.1
python
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - 生成对抗网络(GAN)实例
python·深度学习·tensorflow·tensorflow2
忘忧记1 小时前
excel拆分和合并代码的思路整合和工具打包
python
天才测试猿1 小时前
黑盒测试用例的四种设计方法
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
B站_计算机毕业设计之家1 小时前
机器学习:基于大数据的基金数据分析可视化系统 股票数据 金融数据 股价 Django框架 大数据技术(源码) ✅
大数据·python·金融·数据分析·股票·etf·基金
*才华有限公司*2 小时前
《爬虫进阶之路:从模拟浏览器到破解动态加载的实战指南》
开发语言·python
深蓝电商API2 小时前
爬虫+Redis:如何实现分布式去重与任务队列?
redis·分布式·爬虫·python
我是华为OD~HR~栗栗呀2 小时前
华为OD-23届考研-测试面经
java·c++·python·华为od·华为·面试·单元测试