falsk框架学习1.1

falsk框架学习1.1,第1张

初始化模板
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "

Hello, World!

"
from markupsafe import escape @app.route('/user/') def show_user_profile(username): # show the user profile for that user return f'User {escape(username)}' @app.route('/post/') def show_post(post_id): # show the post with the given id, the id is an integer return f'Post {post_id}' @app.route('/path/') def show_subpath(subpath): # show the subpath after /path/ return f'Subpath {escape(subpath)}'

linux输入命令:

export FLASK_APP=hello
flask run

windows输入命令:

$env:FLASK_APP = “hello”
flask run

如果想要其他电脑也能访问则输入命令:

flask run --host=0.0.0.0

===================================================================
手动分割线

url_for()函数:
from flask import url_for
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/')
def profile(username):
    return f'{username}\'s profile'

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

由此可见url_for函数只看函数名不看映射路径
test_request_context()是一个上下文参数,后面有时间会讲到

修改访问的方法

from flask import request

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

===================================================================
手动分割线

静态文件

静态文件的包为static,
要为静态文件生成 URL,请使用特殊的’static’端点名称:

url_for(‘static’, filename=‘style.css’)

该文件必须以static/style.css

模板render_template()
from flask import render_template
from flask import Flask
app = Flask(__name__)

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

模板的位置应该是这样的

/application.py
/templates
    /hello.html

或者这样的

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

其中py文件是你正在写的程序的位置,总之这个templates包要和你正在写的文件平级

==================================================================
手动分割线

获取参数

获取表单参数使用request.form属性

@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'
    return render_template('login.html', error=error)

获取请求路径中的参数?key=value

searchword = request.args.get('key', '')
文件上传

通过查看 files请求对象的属性来访问这些文件

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')

传输需要在html表单上声明enctype="multipart/form-data"属性,否则就没有文件被传递过来

想知道文件在上传到您的应用程序之前在客户端上是如何命名的,您可以访问该 filename属性。这个值可以被伪造,因此我们使用 secure_filename()

from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['the_file']
        file.save(f"/var/www/uploads/{secure_filename(file.filename)}")
重定向

一看就会就不解释了

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
封装返回对象 make_response()

原始的自定义错误页面是这样的

from flask import render_template

@app.errorhandler(404)
def not_found(error):
    return render_template('error.html'), 404

现在我们要将这个结果返回封装成下响应对象,因为我们即使不封装返回响应对象,这个flask也会自动封装,有时候封装错误会影响我们的返回结果所以我们自己来封装返回对象

from flask import make_response

@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('error.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp
如何返回json结果

默认情况下我们返回的对象是这样写的

@app.route("/me")
def me_api():
    user = get_current_user()
    return {
        "username": user.username,
        "theme": user.theme,
        "image": url_for("user_image", filename=user.image),
    }

这样写很麻烦,因此我们使用jsonify()函数替代字典返回

from flask import jsonify

@app.route("/users")
def users_api():
    users = get_all_users()
    return jsonify([user.to_json() for user in users])
session

有时候我们需要在多个页面跳转并且这多个请求使用同一个用户信息,这就需要使用session,使用session必须设置一个密钥

from flask import session

# 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 f'Logged in as {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 '''
        

'''
@app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index'))

快速生成python密钥的方法,直接终端复制进去就行,这个是根据 *** 作系统加密自动生成的密钥

python -c ‘import secrets; print(secrets.token_hex())’

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/722969.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存