二 Flask快速入门

不打扰是莪最后的温柔 提交于 2020-03-27 10:24:06

1: 外部可访问的服务器:

如果你运行了这个服务器,你会发现它只能从你自己的计算机上访问,网络中其它任何的地方都不能访问。在调试模式下,用户可以在你的计算机上执行任意 Python 代码。因此,这个行为是默认的。如果你禁用了 debug 或信任你所在网络的用户,你可以简单修改调用 run() 的方法使你的服务器公开可用,如下:

app.run(host='0.0.0.0'),这会让操作系统监听所有公网 IP。

2: 调试模式

 

虽然 run() 方法适用于启动本地的开发服务器,但是你每次修改代码后都要手动重启它。这样并不够优雅,而且 Flask 可以做到更好。如果你启用了调试支持,服务器会在代码修改后自动重新载入,并在发生错误时提供一个相当有用的调试器。有两种途径来启用调试模式。一种是直接在应用对象上设置:

 

app.debug = True
app.run()

 

另一种是作为 run 方法的一个参数传入:

 

app.run(debug=True)

 

两种方法的效果完全相同。

注意: 遇到一个问题,程序报错:ModuleNotFoundError: No module named 'markupsafe._compat'。 解决方案:把下面代码拷贝到

# -*- coding: utf-8 -*-
"""
    markupsafe._compat
    ~~~~~~~~~~~~~~~~~~
    Compatibility module for different Python versions.
    :copyright: (c) 2013 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
    text_type = str
    string_types = (str,)
    unichr = chr
    int_types = (int,)
    iteritems = lambda x: iter(x.items())
else:
    text_type = unicode
    string_types = (str, unicode)
    unichr = unichr
    int_types = (int, long)
    iteritems = lambda x: x.iteritems()
View Code

3: 路由

  (1) 基本路由

@app.route('/hello')
def hello():
    return 'Hello World'(2) 代参数路由
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username(3)转换器
@app.route('/post/<int:post_id>')def show_post(post_id):    return 'post %d'  %  post_id

换器有下面几种:

 

int 接受整数
float 同 int ,但是接受浮点数
path 和默认的相似,但也接受斜线

(4) URL_for可以生成URL
@app.route('/user/<username>')def show_user_profile(username):    return ' %s '  % username@app.route('/post/<int:post_id>')def show_post(post_id):   return url_for('show_user_profile', username = "jack")  # 构造URL
4: HTTP请求一个可以处理GET、POST的函数
app.route('/login', methods=['GET', 'POST'])def login():    if request.method == 'POST':        return "POST"    else:        return "GET"
5:静态文件
动态 web 应用也会需要静态文件,通常是 CSS 和 JavaScript 文件。理想状况下, 你已经配置好 Web 服务器来提供静态文件,但是在开发中,Flask 也可以做到。只要在你的包中或是模块的所在目录中创建一个名为 static 的文件夹,在应用中使用 /static 即可访问。给静态文件生成 URL ,使用特殊的 'static' 端点名:
url_for('static', filename='style.css'),这个文件应该存储在文件系统上的 static/style.css。6:模板渲染
Flask 配备了 Jinja2 模板引擎,用来渲染HTML文件。可以使用 render_template() 方法来渲染模板。你需要做的一切就是将模板名和你想作为关键字的参数传入模板的变量。
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)Flask 会在 templates 文件夹里寻找模板hello.html:在templates下创建hello.html:
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello World!</h1>
{% endif %}

7:  取得请求的参数

当前请求的 HTTP 方法可通过 request.method 属性来访问

request.form 属性来访问表单数据( POST 或 PUT 请求提交的数据)。'

request.args.get('key')  可以取得 /login?key="parameter"的key的值 “parameter”

8: 上传文件

获取POST请求的文件,并保存。

f = request.files['the_file']
f.save('/var/www/uploads/uploaded_file.txt')
9: cookie
request.cookies.get('username')
resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')10:重定向和错误
@app.route('/')      def hello_world():    return redirect(url_for('login'))            #重定向
@app.errorhandler(404)                       #错误处理def page_not_found(error):    return "error hhahh"

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!