百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

python3+flask搭建web应用(python flask web开发)

toyiye 2024-08-21 01:55 5 浏览 0 评论

Python学习思路

- 最近因工作需要学习python
- 学习资料:
  - 菜鸟Python3教程https://www.runoob.com/python3/python3-tutorial.html
  - 廖雪峰Python博客https://www.liaoxuefeng.com/wiki/1016959663602400/
  - 以菜鸟为主,廖雪峰补充
- 学习耗时:先花3天左右将菜鸟教程从头到尾过一遍
  - 了解基本环境、语法、库
  - 了解教程的目录章节结构,知道需要的知识去哪一章查询
- 动手实践:
  - 对于有编程经验来说python上手还是非常简单的
  - 但技术细节是过眼烟云
  - 最好的办法是使用他写一个小系统,持续迭代,后续只需查阅之前用法即可
  - 本文的后面部分就是使用Flask框架来搭建、部署一个简单web应用

Flask简介

- 官方文档https://dormousehole.readthedocs.io/en/latest/index.html
- Flask为python语言的轻量级web框架
- Flask vs Django
  - Django大而全
  - Flask更偏向提供轻量级api服务

Flask安装

# 切换python虚拟环境为pyspark
conda activate pyspark

# 安装Flask
pip install Flask

# 检查Flask版本
>>> import flask
>>> flask.__version__
'2.1.2'

Flask应用app.py编写

  • 创建项目目录pytools
  • pytools/app.py:
# coding:utf8

'''
本演示代码参考官方文档quickstart:
https://dormousehole.readthedocs.io/en/latest/quickstart.html
'''
from flask import make_response, redirect, session, url_for
from flask import Flask
from flask import render_template
from flask import request
from werkzeug.utils import secure_filename
from flask import abort
import os

app = Flask(__name__)

# 秘钥设置
app.secret_key=os.urandom(16)

@app.route("/")
def index():
    # 已登录的返回登陆信息
    if 'username' in session:
        # return f'Logged in as {session["username"]}'
        return f'''
        <p>Logged in as {session["username"]}</p>
        <form action="logout">
            <input type="submit" value="Logout" />
        </form>
        '''
    
    # 未登录的重定向到登录页
    return redirect(url_for('login'))

@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 模拟登陆成功设置session
        # 然后重定向到index
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    else:
        # 返回登陆页
        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'))

# 接口路径参数、查询参数、cookies使用演示
@app.route("/hello/")
@app.route("/hello/<name>")
def hello(name=None):
    print('request=', request)
    searchWord = request.args.get('key', '')
    print('searchWord=', searchWord)
    token = request.cookies.get('token', '')
    print(f'token={token}')

    # return render_template('hello.html', name=name)

    rt = render_template('hello.html', name=name)
    resp = make_response(rt)
    resp.set_cookie('token', 'the_token')
    return resp

# 文件上传演示
@app.route("/upload", methods=['GET', 'POST'])
def upload():
    file = request.files['file']
    # 获取上传文件的源文件名
    file.save(f'/home/dev/test/upload/{secure_filename(file.filename)}')
    return "success"

# 404页面演示
@app.route("/404", methods=['GET', 'POST'])
def error():
    abort(404)

# 404页面设置
@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('404.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp

# Restful API演示: 返回JSON
@app.route("/me")
def me_api():
    return {
        "username": "M",
        "theme": "theme",
        "image": url_for("static", filename="style.css"),
    }

if __name__ == '__main__':
    print('app.run()...')
    app.run(port=5000)

pytools/templates/hello.html:

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

pytools/templates/404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Not Found</title>
</head>
<body>
    Page Not Found !
</body>
</html>

pytools/static/style.css

 /* 无内容 */

开发环境运行Flask应用

方式一:使用flask运行

# 切换到app.py目录
cd pytools 

#设置环境变量FLASK_APP
export FLASK_APP=app #不设置默认为app

#运行
flask run

运行结果:
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

注意: 此种方式不会执行__name__ == '__main__'的内容

方式二:使用python运行

# 通过python -m app 或 python app.py 

# 切换到app.py目录
cd pytools

#python -m app
python app.py

运行结果:
app.run()...
 * Serving Flask app 'app' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:8080 (Press CTRL+C to quit)

通过运行输出日志可见LISTEN PORT为8080

注意: 此种方式会执行__name__ == '__main__'的内容

uWSGI服务器安装

uwsgi官方文档: https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html

# 切换到使用的python虚拟环境(我这里是pyspark)
conda activate pyspark

# 通过pip安装uwsgi
pip install uwsgi
# 报错找不到libpython3.9.a
# => 是因为python觉得python.xx.a文件大家日常使用较少,所以在新版本中默认不生成python.xx.a文件

# 因此需要编译python源代码来生成libpython3.9.a文件
# 下载python3.9.12版本源代码(我本地anaconda3 python版本为3.9.12)
wget https://www.python.org/ftp/python/3.9.12/Python-3.9.12.tgz

#解压
tar xzvf Python-3.9.12.tgz  

#进入源码目录
cd Python-3.9.12 

#编译器配置安装目录
./configure --prefix=/tmp/python3.9.12 

#注意不要带上--enable-optimizations参数,会导致gcc版本问题
#./configure --prefix=/tmp/python3.9.12 --enable-optimizations

#编译
make 

#安装,会安装在之前设置的/tmp/python3.9.12目录
make install 

#进入安装目录
cd /tmp/python3.9.12 

# 复制libpython3.9.a到指定的目录(pip install uwsgi报错会提示在config-3.9-x86_64-linux-gnu目录找不到libpython3.9.a文件)
cp libpython3.9.a /export/server/anaconda3/envs/pyspark/lib/python3.9/config-3.9-x86_64-linux-gnu/

# 重新执行uwsgi安装
pip install uwsgi
#继续报错: collect2: error: ld returned 1 exit status
#类似问题是gcc或依赖库版本不兼容导致
#查询资料后给出解决办法是使用conda来安装uwsgi
conda install uwsgi
#使用conda安装还是失败,查询资料后还是依赖的库或版本不兼容导致
#给出解决办法是设置conda的channel(类似maven仓库源)
#然后更新conda
#然后重新安装
#conda channel具体可参考https://www.jianshu.com/p/eba58694537b

#设置channel为conda-forge
conda config --add channels conda-forge

#查看当前channels
conda config --get channels

# 安装conda
conda install conda

# 更新conda
conda update conda

# 重新安装uwsgi
conda install uwsgi
安装成功

#查看uwsgi版本
uwsgi --version
2.0.20

#查看uwsgi对应python版本
uwsgi --python-version
3.9.12

创建uwsgi应用配置文件config.ini

pytools/config.ini

#在项目根目录(pytools)创建配置文件config.ini

[uwsgi]
master=true

#python代码热更新
py-autoreload=1

#uwsgi启动时,所使用的地址和端口(这个是http协议的)
http=0.0.0.0:8000

#指向网站目录
chdir=/home/dev/test/pyspark/pytools

#python 启动程序文件
wsgi-file=app.py

#python 程序内用以启动的application 变量名
callable=app

#处理器数
processes=4

#线程数
threads=2

uid=dev
gid=dev

# uwsgi的进程名称前缀
procname-prefix-spaced=etd 

# 退出uwsgi是否清理中间文件,包含pid、sock和status文件
vacuum=true 

# socket文件,配置nginx时候使用
# socket=%(chdir)/uwsgi/uwsgi.sock
# status文件,可以查看uwsgi的运行状态
#stats=%(chdir)/uwsgi/uwsgi.status 
# pid文件,通过该文件可以控制uwsgi的重启和停止
pidfile=%(chdir)/uwsgi/uwsgi.pid 
# 日志文件,通过该文件查看uwsgi的日志
daemonize=%(chdir)/uwsgi/uwsgi.log 

生产运行

#进入项目根目录
cd pytools

#创建uwsgi目录
mkdir uwsgi

#启动
uwsgi config.ini 
[uWSGI] getting INI configuration from config.ini

#查看进程
ps -ef|grep etd
dev       9388 27859  0 21:05 ?        00:00:02 etd uWSGI worker 1
dev       9389 27859  0 21:05 ?        00:00:02 etd uWSGI worker 2
dev       9392 27859  0 21:05 ?        00:00:02 etd uWSGI worker 3
dev       9393 27859  0 21:05 ?        00:00:02 etd uWSGI worker 4
dev       9394 27859  0 21:05 ?        00:00:00 etd uWSGI http 1
root     20149 11597  0 21:47 pts/5    00:00:00 grep --color=auto etd
dev      27859     1  0 20:14 ?        00:00:11 etd uWSGI master

uwsgi --ini uwsgi.ini # 启动
uwsgi --reload uwsgi.pid # 重启
uwsgi --stop uwsgi.pid # 关闭

访问

#### 访问
浏览器访问 http://ip:8000/返回登录页面



后续就可以在此基础上继续试验python了...

上一张Flask:

相关推荐

# Python 3 # Python 3字典Dictionary(1)

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,格式如...

Python第八课:数据类型中的字典及其函数与方法

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值...

Python中字典详解(python 中字典)

字典是Python中使用键进行索引的重要数据结构。它们是无序的项序列(键值对),这意味着顺序不被保留。键是不可变的。与列表一样,字典的值可以保存异构数据,即整数、浮点、字符串、NaN、布尔值、列表、数...

Python3.9又更新了:dict内置新功能,正式版十月见面

机器之心报道参与:一鸣、JaminPython3.8的热乎劲还没过去,Python就又双叒叕要更新了。近日,3.9版本的第四个alpha版已经开源。从文档中,我们可以看到官方透露的对dic...

Python3 基本数据类型详解(python三种基本数据类型)

文章来源:加米谷大数据Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在Python中,变量就是变量,它没有类型,我们所说的"类型"是变...

一文掌握Python的字典(python字典用法大全)

字典是Python中最强大、最灵活的内置数据结构之一。它们允许存储键值对,从而实现高效的数据检索、操作和组织。本文深入探讨了字典,涵盖了它们的创建、操作和高级用法,以帮助中级Python开发...

超级完整|Python字典详解(python字典的方法或操作)

一、字典概述01字典的格式Python字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。字典的每个键值key=>value对用冒号:分割,每个对之间用逗号,...

Python3.9版本新特性:字典合并操作的详细解读

处于测试阶段的Python3.9版本中有一个新特性:我们在使用Python字典时,将能够编写出更可读、更紧凑的代码啦!Python版本你现在使用哪种版本的Python?3.7分?3.5分?还是2.7...

python 自学,字典3(一些例子)(python字典有哪些基本操作)

例子11;如何批量复制字典里的内容2;如何批量修改字典的内容3;如何批量修改字典里某些指定的内容...

Python3.9中的字典合并和更新,几乎影响了所有Python程序员

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

Python3大字典:《Python3自学速查手册.pdf》限时下载中

最近有人会想了,2022了,想学Python晚不晚,学习python有前途吗?IT行业行业薪资高,发展前景好,是很多求职群里严重的香饽饽,而要进入这个高薪行业,也不是那么轻而易举的,拿信工专业的大学生...

python学习——字典(python字典基本操作)

字典Python的字典数据类型是基于hash散列算法实现的,采用键值对(key:value)的形式,根据key的值计算value的地址,具有非常快的查取和插入速度。但它是无序的,包含的元素个数不限,值...

324页清华教授撰写【Python 3 菜鸟查询手册】火了,小白入门字典

如何入门学习python...

Python3.9中的字典合并和更新,了解一下

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

python3基础之字典(python中字典的基本操作)

字典和列表一样,也是python内置的一种数据结构。字典的结构如下图:列表用中括号[]把元素包起来,而字典是用大括号{}把元素包起来,只不过字典的每一个元素都包含键和值两部分。键和值是一一对应的...

取消回复欢迎 发表评论:

请填写验证码