Flask项目实战01

本文深入探讨了Flask框架的使用,包括pipenv配置、程序实例创建、路由匹配(如字符串、整型、浮点数等转换器)、请求钩子(如before_request、after_request等)、HTTP响应状态码及重定向、响应格式(如JSON、Cookie、Session)、Flask上下文以及HTTP进阶操作。同时,还展示了模板引擎、文件上传和富文本编辑器集成的应用示例。
摘要由CSDN通过智能技术生成

pipenv的是配置与使用

链接: https://zhuanlan.zhihu.com/p/71598248.
链接: https://zhuanlan.zhihu.com/p/104935266.

创建程序实例

可以从flask包中导入Flask类,这个类表示一个Flask程序

from flask import Flask
app = Flask(__name__)

启动项目

pipenv run flask run

路由匹配

from flask import Flask
app = Flask(__name__name)

@app.route('/hello/<name>')
def hello(name):
  # 如果url_for有动态部分,则直接传入参数
  return 'hello %s!'%name

@app.route('/method', methods=['GET',POST])
def method():
  name = request.args.get('name', 'Flask')
  return 'hello %s!'%name

flask的URL变量转换器
转换器说明
string不包含斜线的字符串
int整型
float浮点数
path包含斜线的字符串.static路由的URL规则中的filename说明了这个转换器
uuidUUID字符串

示例:

@app.route('/time/<int:year>')
def go_back(year):
  return 'this is a %s' %year
flask请求钩子
钩子说明
before_first_request注册第一个函数,在处理第一个请求前运行
before_request注册一个函数,在处理每个请求前运行
after_request注册一个函数,如果未处理的异常抛出,会在每个请求结束后运行
tear_down_request注册一个函数,即使有未处理的异常,会在每个请求结束后运行.如果发生异常,会传入异常对象作为参数到注册的函数中
after_this_request在视图函数内注册函数,会在这个请求结束后运行

HTTP响应

HTTP响应状态码
状态码原因短语说明
200OK请求正常处理
201Created请求被处理,并创建一个新资源
204No Content请求处理成功,但无内容返回
301Moved Permanently永久重定向
302Found临时性重定向
304Not Modified请求的资源未被修改,重定向到缓存的资源
400bad Request表示请求无效,即请求报文中存在错误
401unauthorized类似403,表示请求的资源需要获取授权信息,在浏览器中弹出认证弹窗
403Forbidden表示请求的资源被服务器拒绝访问
404Not Found表示在服务器上无法找到请求的资源或URL无效
500Internal Server Error服务器内部发生错误
1.重定向
@app.route('/redirect')
def redire() :
  return redirect('http://www.baidu.com')

@app.route('/redi')
def hi():
  return redirect(url_for('redire')) # 注意这里返回的是路由对应的函数名

@app.route('/404')
def not_found():
  abort(404)
2.响应格式
MIME类型Content-Type:text/html;charset=utf-8
text/plain
text/html
applicatioin/xml
application/json
@app.route('/foo')
def foo():
  data = {
    'name':'Grey Li',
    'gender':'male'
  }
  response = make_response(json.dumps(data))
  response.mimetype = 'application/json'
  return response

@app.route('/foo1')
def foo1():
  
  return jsonify({'name':'Grey Li','gender':'male'})
3.Cookie
set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
@app.route('/setname/<user>')
def set_cookie(user):
  response =make_response(url_for('redire'))
  response.set_cookie('user', user)
  return response
@app.route('/usecookie')
def use_cookie():
  name = request.args.get('name')
  if name is None:
    # 从cookie中获取name值
    name = request.cookies.get('user', 'human')
  return '<h1>hello, %s</h1>' % name 
4.session
@app.route('/register')
def use_sessioin():
  # 写入session
  session['logged_in'] = True

  return redirect(url_for('login'))

@app.route('/login')
def login():
  name = request.args.get('name')
  if name is None:
    name = request.cookies.get('name', 'Human')
    response = '<h1>Hello, %s!</h1>' %name
  
  # 根据用户的认证返回不同的内容
  if 'logged_in' in session:
    response += '[Authenticated]'
  else:
    response += '[not Authenticated]'
  return response

@app.route('/logout')
def logout():
  if 'logged_in' in session:
    session.pop('logged_in')
  return redirect(url_for('login'))

Flask上下文

上下文全局变量
变量名上下文类型说明
current_app程序上下文只想处理请求的程序实例
g程序上下文替代Python的全局变量用法,确保仅在当前请求中可用.用于存储全局数据,每次请求会重设
request请求上下文封装客户端发出的请求报文数据
session请求上下文用于记住请求之间的数据,通过签名的cookie实现
from flask import Flask,g
@app.before_request
def get_name():
    g.name = 'abc'
激活上下文
  • 使用flask run 命令启动程序时
  • 是永久的app.run()方法启动程序时
  • 执行使用@app.cli.command()装饰器注册的flask命令时
  • 使用flask shell命令来启动Python Shell

当请求进入时,Flask会自动激活请求上下文.这时我们可以使用request和session变量

上下文钩子

提供了一种teardown_appcontext钩子,它注册的回调函数会在程序上下文以及请求上下文被销毁时调用,比如,在请求结束后销毁数据库连接.

@app.teardown_appcontext
def teardown_db(exception):
	db.close()

HTTP进阶

获取上一个页面的url

(1) HTTP referer

return redirect(request.referrer or url_for('hello))
# request.full_path  , 获得所有的请求

模板

app = Flask(__name__, template_folder='templates', static_folder="****",static_url_path="****") 在最开始的这句话中,template_folder后面一定要跟上templates;

文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/upload" enctype ="multipart/form-data" method="post">
        <input  type="file" name="file"/>
        <button type="submit">提交</button>
    </form>
</body>
</html>
# 上传文件的路径
app.config['UPLOAD_PATH'] = os.path.join(app.root_path, 'uploads')
# 上传文件大小限制
app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 *1000
# 上传文件的后缀名限制
ALLOWED_EXTENSIONS = { 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# 上传文件
@app.route('/upload', methods = ['get', 'post'])
def upload():
    f = request.files['file']
    if f and allowed_file(f.filename):
        f.save(os.path.join(app.config['UPLOAD_PATH'] ,secure_filename(f.filename)))
    else:
        return 'file upload failed'

    return "file upload success"
多文件上传
    <form action="/multipleupload" enctype ="multipart/form-data" method="post">
        <input type="file" name="filelist" multiple>
        <button type="submit">提交</button>
    </form>
@app.route('/multipleupload', methods = ['get', 'post'])
def multiple_upload():
    files = request.files.getlist('filelist')
    for f in files:
        if f and allowed_file(f.filename):
            f.save(os.path.join(app.config['UPLOAD_PATH'] ,secure_filename(f.filename)))
        else:
            return 'file upload failed'
    return 'file upload success'
使用Flask-CKEditor集成富文本编辑器\

需要使用插件flask-ckeditor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值