基于python的web框架 Flask 入门基础知识【1】

        Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。

目录

一、项目环境搭配以及安装运行

1.下载安装

 2.最小的应用

3.运行应用 

4.运行结果

4.1 外部可见的服务器 

二、路由

 三、http请求

 3.1静态文件

3.2渲染模板

 3.3操作请求数据

四、文件上传

五、Cookies

5.1读取 cookies:

5.2储存 cookies:

六、重定向和错误

6.1定制出错页面

 七、关于响应response

八、会话、消息、日志及 json

8.1JSON 格式的 API

8.2会话

8.3消息闪现

8.4日志

8.5集成 WSGI 中间件


一、项目环境搭配以及安装运行

1.下载安装

创建项目及虚拟环境

$ mkdir myproject
$ cd myproject
$ python3 -m venv venv

激活虚拟环境

venv\Scripts\activate

pip install Flask

(venv) D:\CODE\VSCODE\python\myproject>pip install Flask

 2.最小的应用
from flask import Flask   #导入flask类 该类的实例将会成为我们的 WSGI 应用
app = Flask(__name__)     #创建一个该类的实例 第一个参数是应用模块或者包的名称

@app.route('/')           #然后我们使用 route() 装饰器来告诉 Flask 触发函数的 URL
def hello_world():        #函数名称被用于生成相关联的 URL   
    return 'Hello, World!' #返回需要在用户浏览器中显示的信息
3.运行应用 

该应用运行在windows系统中。

1.set FLASK_APP=hello.py               
2. flask run

4.运行结果

根据提示运行结果可以在 http://127.0.0.1:5000  访问

这样就启动了一个非常简单的内建的服务器。

4.1 外部可见的服务器 

运行服务器后,会发现只有你自己的电脑可以使用服务,而网络中的其他电脑却 不行。缺省设置就是这样的,因为在调试模式下该应用的用户可以执行你电脑中 的任意 Python 代码。

如果你关闭了调试器或信任你网络中的用户,那么可以让服务器被公开访问。只要在命令行上简单的加上 --host=0.0.0.0 即可:

$ flask run --host=0.0.0.0

这行代码告诉你的操作系统监听所有公开的 IP 。

二、路由

使用 route() 装饰器来把函数绑定到 URL:

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'

还可以动态变化 URL 的某些部分, 还可以为一个函数指定多个规则。

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(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('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)

转换器类型: 

 

 三、http请求

一个路由默认回应 GET 请求。 可以使用 route()装饰器的 methods 参数来处理不同的 HTTP 方法:

from flask import Flask,request   
app = Flask(__name__) 

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()
 3.1静态文件

静态文件位于应用的 /static 中。使用特定的 'static' 端点就可以生成相应的 URL

url_for('static', filename='style.css')

 这个静态文件在文件系统中的位置应该是 static/style.css 。

3.2渲染模板

 使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值