Flask 基础 和 快速部署docker
本文发布于 604 天前。

以下内容部分转载自:《Python框架Flask基础教程》

路由

@app.route('/')
def index():  # put application's code here
    return {"username":"Jacky"}

限定请求方式

@app.route('/book/<int:book_id>', methods=['GET'])

带参数路由1

@app.route('/book/<int:book_id>', methods=['GET'])
def book_detail(book_id):
    print(book_id)
    for book in books:
        if book_id == book['id']:
            return book

    return f"ID为{book_id}的图书未找到"

带参数路由 – get

@app.route("/profile")
def profile():
    # 查询字符串 参数传递
    user_id = request.args.get("id")
    if user_id:
        return  "用户个人中心" + str(user_id)
    else:
        return redirect(url_for("index"))

带参数路由 – post

@app.route('/sayhi/', methods=['GET','POST'])
def sayhi():
        name = request.form['name']
        age = request.form['age']
        tel = request.form['tel']
        return '[POST] - {}, {}, and {}'.format(name,age,tel)

字典->Json输出

@app.route('/book/list')
def book_list():
    for book in books:
        book['url'] = url_for("book_detail", book_id=book['id'])
    return jsonify(books)

Jinja2模板

模板渲染

./app.py

@app.route("/about")
def about():
    context = {
        "username": "Saki",
        "books": books
    }
    return render_template("about.html", **context)

./templates/about.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>关于我们</title>
</head>
<body>
    <h1>我是IKK</h1>
    <h2>User: {{ username }}</h2>
    <h2>User Length: {{ username|length }}</h2>
    <h1>Book list</h1>
    <ul id="books">
        {% for book in books %}
        <li>{{ book.id }}, {{ book.name }}</li>
        {% endfor %}
    </ul>
</body>
</html>

参数容器

使用{{}}来放参数。可以间接访问一个变量的属性或者一个字典的key。关于点.号访问和[]中括号访问,没有任何区别,都可以访问属性和字典的值。

过滤器

使用管道符|来进行使用内部过滤器

获取字符串长度

    <h2>User Length: {{ username|length }}</h2>

列表/元组转字符串

    <p>{{ books }}</p>
    <p>{{ books|join(" - ") }}</p>

控制符

{% … %}:用来装载一个控制语句,例如例子中装载了for循环。

if

判断年龄

{% if age>18 %}
You can view this site.
{% elif age<18 %}
You should not enter the site.
{% else %}
Let me think think.
{% endif %}

for

遍历字典

{% for book in books %}
<li>{{ book.id }}, {{ book.name }}</li>
{% endfor %}

注释

{# … #}: 用来放注释。

模版继承

父模板的写法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    // 带参数的block
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
<ul>
    <li>
        <a href="/">首页</a>
    </li>
    <li>
        <a href="/control">控制</a>
    </li>
    <li>
        <a href="/about">关于</a>
    </li>
</ul>
// 完整的block
{% block body %}{% endblock %}
<footer style="background-color: #ccc;">我是footer</footer>
</body>
</html>

子模板继承

{% extends "base.html" %}

{% block title %}
年龄验证
{% endblock %}

{% block body %}
    {% if age>18 %}
    You can view this site.
    {% elif age<18 %}
    You should not enter the site.
    {% else %}
    Let me think think.
    {% endif %}
{% endblock %}

静态文件配置

{% block head %}
    <link rel="stylesheet" href="{{ url_for('static',filename='css/index.css') }}">
{% endblock %}

蓝图

将项目进行模块划分。
建立appspython库文件夹,
couse.py

from flask import Blueprint

# 设置url前缀
bp = Blueprint("course", __name__, url_prefix="/course")

@bp.route('/list')
def course_list():
    return "课程列表"

app.py

from flask import Flask
from apps.book import bp as book_bp
from apps.course import bp as course_bp
from apps.user import bp as user_bp

app = Flask(__name__)
app.register_blueprint(book_bp)
app.register_blueprint(course_bp)
app.register_blueprint(user_bp)

@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


if __name__ == '__main__':
    app.run()

HTTP Basic Auth

from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
users = [
    {'username': 'aa', 'password': 'bb'},
    {'username': 'user', 'password': 'pass'},
    {'username': 'admin', 'password': '123'}
]

@auth.get_password
def get_password(username):
    for user in users:
        if user['username'] == username:
            return user['password']
    return None

@app.route('/')
@auth.login_required
def home():  # put application's code here
    ...

@app.route("/search")
@auth.login_required
def search():
    ...

封装docker

- weiwei
| – app
| | – data
| | – static
| | – tempaltes
| | – app.py
| | – uwsgi.ini
| – Dockerfile
| – requiements.txt

uwsgi.ini

[uwsgi]
module = app
callable = app
processes = 5

dockerfile

FROM tiangolo/uwsgi-nginx-flask:python3.6
COPY requirements.txt requirements.txt 
RUN pip install --no-cache-dir -r requirements.txt
COPY ./app /app

docker commands

build

sudo docker build -t 'weiwei' .

run

docker container run --name weiwei001 --rm -d -p 19001:80 -v /share/CACHEDEV1_DATA/Container/weiwei/data:/app/data -it weiwei

kill

docker container kill weiwei001

remove

docker image rm weiwei
标题:Flask 基础 和 快速部署docker
作者:IKK
除转载和特殊声明外,所有文章采用 CC BY-NC-SA 4.0协议
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇