python
下载
版本问题
amd64才是64位;普通的exe文件是32位的
配置环境变量
linux
- 
1:确定作用范围
当前用户:vim ~/.bashrc
所有用户:vim /etc/profile - 
2:添加内容
 
# python的目录,可通过whereis python[3] 查看
export PYTHONPATH=$PYTHONPATH:python的目录
- 3:使生效 source ~/.bashrc 或者 source /etc/profile
 
pip
类似maven的三方依赖管理器
下载时指定镜像
pip install fastapi -i https://mirrors.aliyun.com/pypi/simple/
配置国内镜像
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
http://pypi.douban.com/simple/ 豆瓣
http://mirrors.aliyun.com/pypi/simple/ 阿里
http://pypi.hustunique.com/simple/ 华中理工大学
http://pypi.sdutlinux.org/simple/ 山东理工大学
http://pypi.mirrors.ustc.edu.cn/simple/ 中国科学技术大学
https://pypi.tuna.tsinghua.edu.cn/simple/ 清华大学
https://pypi.hustunique.com/ 华中科技大学
http://mirrors.cloud.tencent.com/pypi/simple 腾讯
https://repo.huaweicloud.com/repository/pypi/simple/ 华为
————————————
语法
函数
def
匿名函数
lambda函数
只能临时使用一次,只能是一行
形参
- 关键字可变长参数
- 语法:def demo(**arg) #
 
 
点击查看代码
def dict_param(**arg):
    print(arg)
dict_param(age=33,addr='北京大道',line='川藏线')
- 可变长参数
- 语法:def demo(*arg) #参数类型为元组
 
 - 函数定义时,可以设置默认值
 - 可以指定传参,不按顺序传
 
点击查看代码
def get_nums(name='hello',num=2,age=33):
    print(f'{name}, {num},{age}')
    return 1,'hello'
# 第一种写法:nums类型为元组tuple
nums = get_nums(num=55,name='乱序',age=33)
返回值
*不管return与否,都有返回值,函数未显示调用return,则隐式返回None
*可以返回多个值用逗号隔开
None
java的Null
判断非null语法:
if not None:
反射
判断类是否有该属性
点击查看代码
#coding:utf-8
from a import *
cat = Cat('kitty')
print cat.name
cat.sayHi()    #调用实例方法
print dir(cat)
if hasattr(cat, 'name'): #检查实例是否有这个属性
    setattr(cat, 'name', 'tiger') #same as: a.name = 'tiger'
    print getattr(cat, 'name') #same as: print a.name
    
getattr(cat, 'sayHi')()
标识符
- 命名规则:只能由数字、字母、下划线组成
 - 不能以数字开头
 - 不能使用保留关键字
 - 严格区分大小写
 
关键字:None elif not pass raise assert yield global del def lambda with nonlocal
命名规范
- 见名知义
 - 大驼峰
 - 小驼峰
 - 下划线 (car_name)
 
注释
单行注释: #
多行注释: 成对的3个单(双)引号

关键字
- global
变量作用域,将函数内的局部作用域,提升为全局作用域。 
数据类型
- 数字
int(整型)
float(浮点型) - 布尔型 bool (True,False)大写
 - 字符串 str
 
列表 list [3,2,4]
类似java的List,可变长列表,元素为Object
下标从0开始,负数代表逆序(从-1开始)
api
- index(value)
- 返回下标值, 不存在,会抛异常,需要try,代码示例:
 
 
点击查看代码
try:
    print(arr.index(9))
except ValueError:
    print("9元素不存在!!")
元组 tuple (2, 1, 5)
- 定义
- 类似java数组,容量定长,可重复的容器,元素不可修改(元素为list,可以对list的元素修改)
 
 
语法
获取2维数组内容,语法和list一样,示例:num = tuple[0][0]
单个元素
单个元素末尾需要加上逗号,不然类型就是str
tt = ("单个元素末尾需要加上逗号,不然类型就是str",)
- 集合 set
 - 字典 dict 键值对
 
字符格式化
f写法
- 3.6以后的语法
 
- f'{表达式}'
 
print(f'名字:{name},年龄{age}岁,体重{weight}')
占位符写法
| 格式符号 | 转化 | 用法 | 
|---|---|---|
| %s | 字符串 | print("名字:%s" %name) | 
| %d | 有符号的十进制整数 | |
| %u | 无符号的十进制整数 | |
| %f | 浮点数 | print("体重:%.3f" %weight) # 指定保留3位(默认保留6位) | 
| %c | 字符 | |
| %e | 科学计数法(小写'e') | |
| %E | 科学计数法(大写'e') | |
| %g | %f和%e的简写 | |
| %G | %f和%E的简写 | 
- 多种格式一起
 
print("名字:%s,年龄%s岁,体重%s" %(name, age, weight))
django
- 安装django
 
pip install django
// 安装指定版本
pip install django==版本号
- 创建项目工程
 
// cd 到项目父目录,
// 工程名 文件夹会自动创建
django-admin startproject 工程名
- 启动
 
// 先cd 到manage.py目录
// 执行下面命令,端口默认8000
python manage.py runserver
fastapi
jinja2
模板引擎
1:把pip更新到最新版本:
下载离线whl: pip-23.2.1-py3-none-any.whl
2: 执行更新命令:python.exe -m pip install --upgrade pip
3:需要3个离线whl,详情见“模板引擎”
4:代码示例:
点击查看代码
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from starlette.requests import Request
import uvicorn
import os
from starlette.staticfiles import StaticFiles
app=FastAPI()
# index2.html 相较于run.py的目录位置
tmp = Jinja2Templates('static')
app.mount('/aa', StaticFiles(directory = 'static'), name='static')
@app.get('/')
async def write(request: Request):
   txt = tmp.TemplateResponse('index2.html',
                              {'request': request,
                               'users': [
                                   {'age': 18, 'name': '张三'},
                                   {'age': 34, 'name': '江风'}
                               ],
                               'title': '标题'}
                              )
   # print(type(txt.body))
   # print(type(txt.charset))
   return txt
if __name__ == "__main__":
    uvicorn.run("run:app", host="127.0.0.1", port=9090, reload=True)
5-2:截图(web工程):

5-2:截图(普通工程):

数据校验
Path: 给路径参数使用 '/api/{xxx}'
Query: 单个的请求参数使用 "?name=zhans"
Field: 请求体的属性使用

离线安装
- whl文件官网下载地址;https://pypi.org/
 - 文件后缀:.whl
 - 依赖关系:
 
下面的依赖上面

安装步骤
0: 下载顺序,先下fastapi,pip install是提示缺什么库,再去下缺失库的指定版本
1:搜索

2: 下载历史版本

3:下载离线库(.whl)

4: install 命令
示例:
pip install fastapi-0.100.0-py3-none-any.whl
5:下载成功截图

6;考一个fastapi示例代码,执行命令: uvicorn openapi:app --reload
成功后控制台展示ip和端口

6:如提示:uvicorn : 无法将“uvicorn”项识别为 cmdlet、函数
解决办法:见:下面黄色的“解决办法”
在线安装
下载fastapi依包赖
pip install fastapi -i https://mirrors.aliyun.com/pypi/simple
因为fastapi启动依赖于uvicorn,所以我们还需要安装uvicorn。
pip install uvicorn -i https://mirrors.aliyun.com/pypi/simple
提供api访问路径验证
`from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
`
启动命令
uvicorn main:app --reload
提示uvicorn不是命令,因为没有将uvicorn.exe文件放置在C:\Python310\Scripts
注意查看控制台这句话
WARNING: The script uvicorn.exe is installed in 'C:\Users\I\AppData\Roaming\Python\Python312\Scripts' which is not on PATH.
解决办法:
磁盘搜索uvicorn.exe,将该文件复制到Python安装目录下的Scripts
如图:

再执行uvicorn main:app --reload,控制台打印IP+ 端口,则服务启动成功!

swagger
离线如何展示
取名随机字符-推荐

取名staitic-不推荐
亲测,一定可以的,如果无网跟着操作还不行,一定是项目静态路径改过
可以单独起一个纯净的fastapi项目,测好后,再移到项目中
- 
需要下载2个文件:swagger-ui.css,swagger-ui-bundle.js(联网时响应的去除换行)
 - 
文件存放位置:
![image]()
 - 
关键2步:修改源码和挂载静态文件(改过静态资源的情况)
![image]()
 - 
纯净项目测试效果
 
请求体
- 属性文档写法
![image]()
 
pycharm
设置文件模板代码
- 在setting中的Editor中找到File and Code Templates
 
模板引擎Jinja2
whl离线安装包
- 3个文件
 
点击查看代码
# 去官网pypi.org下载,fastapi基于0.83.0
# 从上到下执行
pip install wheel-0.38.4-py3-none-any.whl
pip install MarkupSafe-2.1.3-cp37-cp37m-win_amd64.whl
pip install Jinja2-3.1.2-py3-none-any.whl
语法
- if 语法
 
点击查看代码
{% if user %}
   {{user.nick}} 年龄:{{user.age}}
{% endif%}
- for循环
 
点击查看代码
{%  for li in userList %}
	{{li.name}}
{% endfor %}
- 继承
 
点击查看代码
{% extends "common/layout.html" %}
{% block content %}
	hello jinja2
{% endblock%}
api
re 正则
- sub函数
替换Inp中的收尾标签 
点击查看代码
space_str = "@user car house _beg_2"
space = re.sub(r'(@)|(_beg_\d+$)|(_beg)',"",space_str)
space = space.strip().replace(" ", "_")
print("space:", space)
file
写
- 推荐写法:with加上'w',可自动调用flush和colse
 
点击查看代码
with open("../static/write_demo.txt",'w',encoding='utf-8') as fw:
    txt = fw.write("hello open")
time.sleep(600000)
print("执行完了吗")
write后要flush,这样能及时将内容写入文件中
- write函数
 - flush
 
with open() as f:
自动会执行close
点击查看代码
with open("../static/hello.txt",encoding='utf-8') as f:
    for line in f:
    # 读取每一行
    print(line)
- close
内置了flush功能
作用:解除程序对该文件的占用
open后一定要关闭,不然会一直被占用,其他程序无法删除、修改文件名(里面的字符可以改)等操作(直到python程序结束) - open
文件路径可以传相对路径 
f = open("../static/index.html",encoding='utf-8')
- for循环遍历每一行
 
点击查看代码
for line in f:
    # 读取每一行
    print(line)
                    
                



                
            
        
浙公网安备 33010602011771号