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

先跳过

相关推荐
闻哥17 小时前
Java虚拟机内存结构深度解析:从底层原理到实战调优
java·开发语言·jvm·python·面试·springboot
@––––––17 小时前
力扣hot100—系列6-栈
linux·python·leetcode
Jia ming17 小时前
《智能法官软件项目》—数据可视化模块
python·信息可视化·教学·案例·智能法官软件
Web极客码17 小时前
CentOS 7 删除文件却不释放空间?从 inode、文件描述符到 VFS 的底层原理解析
python·centos·numpy
火红色祥云18 小时前
Python机器学习经典实例_笔记
笔记·python·机器学习
yq19820430115618 小时前
基于Python爬虫原理的Pinterest视频资源获取技术解析与工具实践
爬虫·python·django·音视频
喵手18 小时前
Python爬虫实战:自动化质量护航 - 构建爬虫数据的“熔断与巡检”规则引擎实战!
爬虫·python·自动化·爬虫实战·零基础python爬虫教学·自动化质量护航·数据熔断
一切尽在,你来18 小时前
AI大模型应用开发前置知识:Python 异步编程
python·ai编程
一切尽在,你来18 小时前
LangGraph 概览
人工智能·python·langchain·ai编程
CeshirenTester1 天前
9B 上端侧:多模态实时对话,难点其实在“流”
开发语言·人工智能·python·prompt·测试用例