Python全栈:flask快速入门

简介: Python全栈:flask快速入门

参考 : flask快速入门

http://docs.jinkan.org/docs/flask/quickstart.html

项目结构

a4.1.png

├── flask_demo.py   # 项目主文件
├── secret_key.py
├── static          # 静态文件目录
│   └── main.css
└── templates       # 模板文件目录
    ├── hello.html
    ├── login.html
    └── upload.html

代码文件

flask_demo.py

from flask import Flask
from flask import session, redirect, abort, url_for
from flask import request, render_template, make_response
app = Flask(__name__)
# 主页,登陆后显示登录名
@app.route('/')
def index():
    username = session.get("username")
    app.logger.info("index") # 日志
    return "Hello world %s"%username
# 路由参数变量
@app.route("/user/<username>")
def show_username(username):
    return "username:%s"%username
# 参数转换器
@app.route("/id/<int:uid>")
def show_id(uid):
    return "your id:%d"%uid
# post, get请求
@app.route("/username", methods=["POST", "GET"])
def username():
    if request.method == "POST":
        return "post username"
    elif request.method == "GET":
        return "get username"
    else:
        return "none"
# 模板和静态文件
@app.route("/hello/")
@app.route("/hello/<name>")
def hello(name=None):
    return render_template("hello.html", name=name)
# 表单post参数
@app.route("/login/", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    elif request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        # session会话
        session["username"] = username
        return redirect(url_for("index"))
        # return "username:%s, password:%s"%(username, password)
# 退出登录
@app.route("/logout/")
def logout():
    session.pop("username", None)
    return redirect(url_for("index"))
# 推荐 get参数:http://127.0.0.1:5000/page/?num=4
@app.route("/page/")
def page():
    page_num = request.args.get("num")
    return "num:%s"%page_num
# 文件上传
@app.route("/upload/", methods=["GET", "POST"])
def upload_file():
    if request.method == "GET":
        return render_template("upload.html")
    elif request.method == "POST":
        file = request.files.get("upload-file")
        print(file.filename)
        file.save(file.filename)
        return "文件上传成功"
# 读取存贮 cookies
@app.route("/cookie/")
def cookie():
    username = request.cookies.get("username")
    print(username)
    response = make_response("访问cookie")
    if not username:
        response.set_cookie("username", "mouday")
    return response
# 404 与重定向
@app.route("/notpage1/")
def notpage1():
    return redirect(url_for("notpage2"))
@app.route("/notpage2/")
def notpage2():
    abort(401)
# 404页面
@app.errorhandler(404)
def not_find_page(error):
    return "<h1>404</h1>", 404
app.secret_key = r"\xedz\xdf\x1c\xd2\xa7\xdff:6\xef\xf2\x95mL\x18TF\r\x00LM\xec\xa9"
if __name__ == "__main__":
    # 监听所有公网 IP, 开启调试模式
    app.run(host='0.0.0.0', debug=True)

secret_key.py

# 可用于生成 secret_key
import os
print(os.urandom(24))
# b'\xedz\xdf\x1c\xd2\xa7\xdff:6\xef\xf2\x95mL\x18TF\r\x00LM\xec\xa9'

main.css

body{
    background-color: darkgreen;
}

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="/static/main.css" rel="stylesheet" type="text/css" />
</head>
    <body>
        <h1>hello world</h1>
        {% if name %}
            <h2>{{ name }}</h2>
        {% else %}
            <h2>没有名字</h2>
        {% endif %}
    </body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login/" method="post">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit">
</form>
</body>
</html>

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload/" method="post" enctype="multipart/form-data">
    <input type="file" name="upload-file">
    <input type="submit">
</form>
</body>
</html>


相关文章
|
16天前
|
安全 数据库 C++
Python Web框架比较:Django vs Flask vs Pyramid
【4月更文挑战第9天】本文对比了Python三大Web框架Django、Flask和Pyramid。Django功能全面,适合快速开发,但学习曲线较陡;Flask轻量灵活,易于入门,但默认配置简单,需自行添加功能;Pyramid兼顾灵活性和可扩展性,适合不同规模项目,但社区及资源相对较少。选择框架应考虑项目需求和开发者偏好。
|
4天前
|
API 数据库 数据安全/隐私保护
Flask框架在Python面试中的应用与实战
【4月更文挑战第18天】Django REST framework (DRF) 是用于构建Web API的强力工具,尤其适合Django应用。本文深入讨论DRF面试常见问题,包括视图、序列化、路由、权限控制、分页过滤排序及错误处理。同时,强调了易错点如序列化器验证、权限认证配置、API版本管理、性能优化和响应格式统一,并提供实战代码示例。了解这些知识点有助于在Python面试中展现优秀的Web服务开发能力。
22 1
|
4天前
|
SQL 中间件 API
Flask框架在Python面试中的应用与实战
【4月更文挑战第18天】**Flask是Python的轻量级Web框架,以其简洁API和强大扩展性受欢迎。本文深入探讨了面试中关于Flask的常见问题,包括路由、Jinja2模板、数据库操作、中间件和错误处理。同时,提到了易错点,如路由冲突、模板安全、SQL注入,以及请求上下文管理。通过实例代码展示了如何创建和管理数据库、使用表单以及处理请求。掌握这些知识将有助于在面试中展现Flask技能。**
12 1
Flask框架在Python面试中的应用与实战
|
5天前
|
数据安全/隐私保护 Python
Python Flask-Mail实现邮件发送
Python Flask-Mail实现邮件发送
|
10天前
|
数据库 开发者 Python
Python中使用Flask构建简单Web应用的例子
【4月更文挑战第15天】Flask是一个轻量级的Python Web框架,它允许开发者快速搭建Web应用,同时保持代码的简洁和清晰。下面,我们将通过一个简单的例子来展示如何在Python中使用Flask创建一个基本的Web应用。
|
10天前
|
前端开发 数据挖掘 API
使用Python中的Flask框架进行Web应用开发
【4月更文挑战第15天】在Python的Web开发领域,Flask是一个备受欢迎的轻量级Web框架。它简洁、灵活且易于扩展,使得开发者能够快速地构建出高质量的Web应用。本文将深入探讨Flask框架的核心特性、使用方法以及在实际开发中的应用。
|
15天前
|
JavaScript 前端开发 Docker
全栈开发实战:结合Python、Vue和Docker进行部署
【4月更文挑战第10天】本文介绍了如何使用Python、Vue.js和Docker进行全栈开发和部署。Python搭配Flask创建后端API,Vue.js构建前端界面,Docker负责应用的容器化部署。通过编写Dockerfile,将Python应用构建成Docker镜像并运行,前端部分使用Vue CLI创建项目并与后端交互。最后,通过Nginx和另一个Dockerfile部署前端应用。这种组合提升了开发效率,保证了应用的可维护性和扩展性,适合不同规模的企业使用。
|
18天前
|
数据采集 存储 前端开发
Python爬虫如何快速入门
写了几篇网络爬虫的博文后,有网友留言问Python爬虫如何入门?今天就来了解一下什么是爬虫,如何快速的上手Python爬虫。
21 0
|
1月前
|
Python
老男孩&路飞学城Python全栈
老男孩&路飞学城的Python全栈开发重点班由ALEX老师主讲,核心教学内容,100多天课程,近100G资料,含基础到实战。一线技术专家亲授,以案例教学引导学生逐步进入项目实战。
20 1
老男孩&路飞学城Python全栈
|
14天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。