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

先跳过

相关推荐
水木流年追梦3 分钟前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
财经资讯数据_灵砚智能21 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月12日
人工智能·python·信息可视化·自然语言处理·ai编程
2301_815901971 小时前
C#怎么使用协变和逆变 C#泛型中的in和out关键字协变逆变是什么意思怎么用【语法】
jvm·数据库·python
Pkmer1 小时前
LeetCode 上极少见的工程级滑窗实现
python·leetcode
m0_463672201 小时前
SQL优化SQL关联查询中的排序字段_减少临时空间占用与内存开销
jvm·数据库·python
FreakStudio1 小时前
开源分享|用MicroPython 做了个 AI 小鸡,它会长大,还记得我所有的情绪
python·单片机·嵌入式·面向对象·并行计算·电子diy·电子计算机
iuvtsrt1 小时前
存储过程如何处理海量数据的批处理_循环提交与分段LIMIT结合
jvm·数据库·python
yexuhgu1 小时前
SQL如何检查字符串是否存在:INSTR与LOCATE函数使用
jvm·数据库·python
2301_783848651 小时前
SQL如何用SQL子查询实现关联报表生成_嵌套逻辑关联多表
jvm·数据库·python
八月欢喜1 小时前
【Facebook】 实时消息监控难点解析
javascript·python·facebook