python web

python web

Django

Django 是一个由 Python 编写的一个开放源代码的 Web 应用框架

入门

安装

pip

1
pip install django

pycharm

1
软件包搜Django --> 安装软件包

安装完后会在Lib目录下下载django源码,在Scripts下生成django-admin.exe用于生成django项目

创建项目

cmd

1
2
# 进到要创建项目的目录
django-admin startproject 项目名称

pycharm

1
文件 --> 新建项目 --> Django --> 输入项目名创建项目

项目目录说明

1
2
3
4
5
6
7
|-- 项目同名文件夹
| |-- __init__.py # 空的,标记这个软件包为python软件包
| |-- asgi.py # 接收网络请求(异步)
| |-- settings.py # 项目的配置文件
| |-- urls.py # 访问路径和函数间的映射关系
| `-- wsgi.py # 接收网络请求(同步)
`-- manage.py # 项目管理,启动项目,创建app,数据管理

App

类似java中maven项目的模块

创建app

1
2
# 在项目目录下
python manage.py startapp <app名>

注册app

1
在settings.py文件的INSTALLED_APPS中添加app的apps.py中的启动类

app目录结构

1
2
3
4
5
6
7
8
|-- app名
| |-- __init__.py
| |-- admin.py # django默认提供了admin后台管理
| |-- apps.py # app启动类
| |-- models.py # **对数据库操作**
| |-- tests.py # 单元测试
| |-- views.py # **放与请求路径对应的函数**
`-- manage.py

第一个项目

  1. 创建app
1
python manage.py startapp HelloWorld
  1. settings.py的INSTALLED_APPS中注册app
1
2
3
4
5
6
7
8
9
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'HelloWorld.apps.HelloworldConfig', # 注册app
]
  1. urls.py中加入映射
1
2
3
4
5
urlpatterns = [
path('admin/', admin.site.urls),
# 访问路径和函数的映射
path('index/', views.index),
]
  1. 在views.py中编写对应函数
1
2
def index(request):
return HttpResponse("Hello World")
  1. 启动
1
2
3
python manage.py runserver

pycharm 中绿色三角
  1. 页面访问localhost:8000/index

模板

在app下建立templates目录来放置网页文件

static目录放静态文件

在函数中使用return render(request, "文件名")来返回网页

搜索网页文件顺序

  1. 优先项目根目录的templates中找

    要在配置文件的TEMPLATES中标识'DIRS': [os.path.join(BASE_DIR, 'templates')]

  2. 根据app注册顺序,在每个app的templates中找

Flask

小案例

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)

@app.route("/add/user", methods=["GET", "POST"])
def add_user():
if request.method == 'GET':
return render_template("add_user.html")

# 保存到mysql
conn = get_conn()
insert(conn, request)
conn.close()

return "添加成功"


@app.route("/show/user")
def show_user():
conn = get_conn()
all_info = get_all(conn)
conn.close()
print(all_info)

return render_template("show_user.html", data_list=all_info)

# 获取游标
def get_conn():
conn = pymysql.connect(host="127.0.0.1",
port=3306,
user='root',
password='123456',
charset='utf8',
db='pyconn')

return conn


# 插入数据
def insert(conn, request):
info = {
"user": request.form.get("user"),
"pwd": request.form.get("pwd"),
"mobile": request.form.get("mobile"),
}
cursor = conn.cursor()
sql = "insert into admin(username, password, mobile) values (%s, %s, %s)"
cursor.execute(sql, [info["user"], info["pwd"], info["mobile"]])
conn.commit()


# 获取所有数据
def get_all(conn):
cursor = conn.cursor(pymysql.cursors.DictCursor)
sql = "select * from admin"
cursor.execute(sql)
return cursor.fetchall()


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

前端

添加用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" action="/add/user">
<input type="text" name="user" placeholder="用户名">
<input type="text" name="pwd" placeholder="密码">
<input type="text" name="mobile" placeholder="手机号">
<input type="submit" value="提交">
</form>
</body>
</html>

展示用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>手机号</th>
</tr>
</thead>
<tbody>
{% for item in data_list %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.username }}</td>
<td>{{ item.PASSWORD }}</td>
<td>{{ item.mobile }}</td>
</tr>
{% endfor %}
</tbody>
</table>

</body>
</html>

python web
http://xwww12.github.io/2022/12/02/python/python web/
作者
xw
发布于
2022年12月2日
许可协议