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

先跳过

相关推荐
troy12815 分钟前
Python 基础语法(六):函数与模块、文件操作、异常处理
开发语言·python
小叶肥辉22 分钟前
LangChain链和LangGraph图的学习笔记【四】——(1)调用方法:invoke(2)提示语模板:PromptTemplate
python·langchain·prompt
小兔崽子去哪了31 分钟前
深度学习 2 / CNN 神经网络
后端·python
weixin_4407305040 分钟前
队列QUEUE介绍+类型示例(先进先出、后进先出、优先级高先出、双端进入、生产者+消费者线程)
python·线程·queue
这是程序猿43 分钟前
Java线程池深度剖析:源码原理、核心参数、任务调度与生产调优实战
java·开发语言·python
Web3&Basketball1 小时前
ChatGPT 路由自证:跨客户端实测对照
python·大模型·agent·推理·推理优化
Patrick在香港1 小时前
Claude 工作提醒自动化:香港天文台四个接口三个「更新时间」,警告到期了却还在生效
python·api·claude·数据抓取·香港
用户8356290780511 小时前
Python 实现 Word 文档域的插入与管理
后端·python
quantdash_cc1 小时前
从数据采集到策略消费,股票日内行情管道应该怎么设计?
开发语言·python·数据分析·量化交易·股票数据·quantdash
程序员杰哥1 小时前
UI自动化测试:Jenkins配置
自动化测试·软件测试·python·测试工具·职场和发展·jenkins·测试用例