Python - Flask - 入门

路由基本写法的两种形式

1.

from flask import Flask # 导入包

app = Flask(__name__) # 创建一个Web应用

@app.route('/') # 定义路由(Views),可以理解为定义页面的URL

def index():

return "Hello World" # 渲染页面

 

2.

from flask import Flask, abort, request, jsonify

from flask_restful import reqparse, abort, Api, Resource

app = Flask(__name__)

api = Api(app)

class TODO(Resource):

def get(self,args*):

exec_1()

def post(self,args*):

exec_2()

def put(self,args*):

exec_3()

api.add_resource(Exec,'/<rosdbname>')

 

启动:export FLASK_APP=hello.py python -m flask run --host=0.0.0.0 --port=5000

 

==========================================

路由

URL构建

url_for().函数名称是第一个参数。它可以接受任意个关键字参数,每个关键字参数对应 URL 中的变量。未知变量 将添加到 URL 中作为查询参数。

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

 

@app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user/<username>') def profile(username): return '{}\'s profile'.format(username) with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe'))

 

/ /login /login?next=/ /user/John%20Doe

 

HTTP方法

GET

POST

HEAD

OPTIONS

PUT

DELETE

TRACE

CONNECT 

 

==========================================

静态文件

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

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

 

==========================================

渲染模板

Jinja2

from flask import render_template

@app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name)

 

情形 1 : 一个模块:

/application.py /templates /hello.html

情形 2 : 一个包:

/application /__init__.py /templates /hello.html

 

==========================================

操作请求数据

本地环境

from flask import request with app.test_request_context('/hello', method='POST'): # now you can do something with the request until the # end of the with block, such as basic assertions: assert request.path == '/hello' assert request.method == 'POST'

 

另一种方式是把整个 WSGI 环境传递给 request_context() 方法:

from flask import request with app.request_context(environ): assert request.method == 'POST'

 

请求对象

from flask import request

@app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error)

 

文件上传

用 Flask 处理文件上传很容易,只要确保不要忘记在你的 HTML 表单中设置 enctype="multipart/form-data" 属性就可以了。否则浏览器将不会传送你的文件。

from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ...

如果想要知道文件上传之前其在客户端系统中的名称,可以使用 filename 属性。但是请牢记这个值是 可以伪造的,永远不要信任这个值。如果想要把客户端的文件名作为服务器上的文件名, 可以通过 Werkzeug 提供的secure_filename() 函数:

from flask import request from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/' + secure_filename(f.filename)) ...

 

==========================================

cookies

from flask import request @app.route('/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing.

 

储存 cookies:

from flask import make_response @app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp

 

 

==========================================

重定向和错误

from flask import abort, redirect, url_for @app.route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): abort(401) this_is_never_executed()

 

缺省情况下每种出错代码都会对应显示一个黑白的出错页面。使用 errorhandler() 装饰器可以定制出错页面:

from flask import render_template @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404

 

==========================================

响应

 

 

==========================================

会话

除了请求对象之外还有一种称为 session 的对象,允许你在不同请求 之间储存信息。这个对象相当于用密钥签名加密的 cookie ,即用户可以查看你的 cookie ,但是如果没有密钥就无法修改它。

 

from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index'))

 

 

==========================================

消息闪现

 

==========================================

日志

 

app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值