一坯临、venv環(huán)境管理
1霍殴、 venv 虛擬環(huán)境的優(yōu)點(diǎn)
- 獨(dú)立的 Python 環(huán)境涮帘,不會(huì)產(chǎn)生沖突
- 有助于包的管理
- 刪除和卸載方便
2单寂、venv 使用方法
- 創(chuàng)建虛擬環(huán)境
- 激活虛擬環(huán)境
- 安裝 Python 包
2.1 venv 創(chuàng)建虛擬環(huán)境
- 執(zhí)行指令
python3 -m venv test
2.2 venv 激活虛擬環(huán)境
- 切換指定件夾
- Windows:/Scripts/
- macOS:/bin/
- 執(zhí)行指令:
activate
# Windows 系統(tǒng)激活虛擬環(huán)境
cd test
cd Scripts
activate
# macOS系統(tǒng)激活虛擬環(huán)境
cd test
cd bin
source actiavte
# 或者一步到位
source ./test/bin/acitvate
2.3 venv 安裝 Python 包
- Python 版本選擇
- 進(jìn)入 python2.7 環(huán)境:
python2
- 進(jìn)入 python3.x 環(huán)境:
python3
- 進(jìn)入 python2.7 環(huán)境:
- pip 安裝 Python 包
- 安裝 Python2.x 版本的包
- 安裝 Python3.x 版本的包
# 進(jìn)入 python2.7 環(huán)境
python2
# 進(jìn)入 python3.x 環(huán)境
python3
# 安裝 Python2.x 版本的包
pip install xxx
# 安裝 Python3.x 版本的包
pip3 install xxx
2.4venv 退出和刪除
- 退出虛擬環(huán)境:deactivate
- 刪除虛擬環(huán)境:刪除環(huán)境目錄
# Windows和macOS通用的退出指令
deactivate
3贬芥、pyenv安裝
- pyenv:python的多版本安裝工具
- pyenv地址:https://github.com/pyenv/pyenv-installer
- 安裝命令(Mac):
curl https://pyenv.run | bash
- 安裝python:
-
pyenv install -l
(查看所有python版本) pyenv install 2.7.14
pynv install 3.7.0
pyenv install python-2.7.1
-
3.1指定使用版本
- 查看當(dāng)前使用版本:
pyenv version
- 查看所有版本:
pyenv versions
- 指定全局版本:
pyenv global 3.7.0
- 本地設(shè)置,只影響當(dāng)前文件夾:
pyenv local 2.7.14
3.2Python環(huán)境隔離VirtualEnv
virtualenv --no-site-packages venv
. venv/bin/active
pip install selenium
模塊
生成一個(gè)模塊
curl http://www.baidu.com > baidu.html
python2 -m CGIHTTPServer
# python3 -m http.server
二宣决、pip環(huán)境管理
pip 概述
- pip 是 Python 包管理工具
- python2 的 2.7.9 版本開(kāi)始自帶
- python3 的 3.4 版本開(kāi)始自帶
- https://pypi.org/ 托管了大量流行的 Python 包
pip 常用命令
功能 | 指令 |
---|---|
查看 pip 版本 | pip -V |
查看幫助文檔 | pip help |
查看包列表 | pip list |
導(dǎo)出包列表 | pip freeze |
安裝 | pip install 包名 |
升級(jí) | pip install -U 包名 |
卸載 | pip uninstall 包名 |
pip 安裝包
- 普通安裝
- 指定版本
- 從文件中安裝
# 默認(rèn)安裝最新版本
$ pip install pytest
# 執(zhí)行版本
$ pip install pytest==6.2.0
# 從文件清單中批量安裝
$ pip install -r requirments.txt
# 文件格式
pytest==6.2.0
Faker==9.3.1
selenium==3.14.1
pip 升級(jí)包
- 升級(jí)已安裝的 Python 包
$ pip install -U pytest
pip 卸載包
- 卸載 Python 包
# 卸載包
$ pip uninstall pytest
pip 使用鏡像加速
pip install -i 鏡像源
-
國(guó)內(nèi)常用源
- 阿里源:https://mirrors.aliyun.com/pypi/simple/
- 清華源:https://pypi.tuna.tsinghua.edu.cn/simple/
- 豆瓣源:http://pypi.douban.com/simple/
# 使用鏡像 pip install pytest -i https://pypi.douban.com/simple
三蘸劈、常用第三方庫(kù)yaml
1、YAML
- 一種數(shù)據(jù)序列化格式
- 用于人類的可讀性和與腳本語(yǔ)言的交互
- 一種被認(rèn)為可以超越 XML尊沸、JSON 的配置文件
2威沫、YAML 基本語(yǔ)法規(guī)則
- 大小寫(xiě)敏感
- 使用縮進(jìn)表示層級(jí)關(guān)系
- 縮進(jìn)時(shí)不允許使用 Tab 鍵,只允許使用空格
- 縮進(jìn)的空格數(shù)目不重要洼专,只要相同層級(jí)的元素左側(cè)對(duì)齊即可
-
#
表示注釋棒掠,從這個(gè)字符一直到行尾,都會(huì)被解析器忽略
3壶熏、YAML 支持的數(shù)據(jù)結(jié)構(gòu)
- 對(duì)象:鍵值對(duì)的集合句柠,用冒號(hào) “:” 表示
- 數(shù)組:一組按次序排列的值,前加 “-”
- 純量:?jiǎn)蝹€(gè)的棒假、不可再分的值
- 字符串
- 布爾值
- 整數(shù)
- 浮點(diǎn)數(shù)
- Null
- 時(shí)間
- 日期
# 編程語(yǔ)言
languages:
- PHP
- Java
- Python
book:
Python入門(mén): # 書(shū)籍名稱
price: 55.5
author: Lily
available: True
repertory: 20
date: 2018-02-17
Java入門(mén):
price: 60
author: Lily
available: False
repertory: Null
date: 2018-05-11
4溯职、PyYAML
- Python 的 YAML 解析器和生成器
- 官網(wǎng):https://pypi.org/project/PyYAML/
- 安裝:
pip install pyyaml
4.1創(chuàng)建 yaml 文件
import yaml
data = {
"client": {"default-character-set": "utf8"},
"mysql": {"user": 'root', "password": 123},
"custom": {
"user1": {"user": "張三", "pwd": 666},
"user2": {"user": "李四", "pwd": 999},
}
}
# 直接 dump 可以把對(duì)象轉(zhuǎn)為 YAML 文檔
with open('./my.yaml', 'w', encoding='utf-8') as f:
yaml.dump(data, f, allow_unicode=True)
4.2讀取 yaml 文件
import yaml
file_path = './my.yaml'
with open(file_path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
print(data)
四、常用第三方庫(kù)pymysql
1帽哑、pymysql 概述
Python 的數(shù)據(jù)庫(kù)接口標(biāo)準(zhǔn)是 Python DB-API
PyMySQL 是從 Python 連接到 MySQL 數(shù)據(jù)庫(kù)服務(wù)器的接口
PyMySQL 的目標(biāo)是成為 MySQLdb 的替代品
2谜酒、pymysql 安裝
- 使用 pip 安裝
- 使用 Pycharm 界面安裝
pip install pymysql
3、pymysql 連接數(shù)據(jù)庫(kù)
- host:MySQL 服務(wù)器地址
- user:用戶名
- password:密碼
- database:數(shù)據(jù)庫(kù)名稱
- charset:編碼方式妻枕,推薦使用 utf8mb4
# 1.導(dǎo)入庫(kù)
import pymysql
# 2.建立連接
conn = pymysql.connect(host='服務(wù)器地址',
user='用戶名',
password='密碼',
database='數(shù)據(jù)庫(kù)名',
charset="utf8mb4")
# 3.關(guān)閉連接
conn.close()
pymysql 連接數(shù)據(jù)庫(kù)
- 封裝獲取連接的函數(shù)
import pymysql
# 1.封裝建立連接的對(duì)象
def get_conn():
conn = pymysql.connect(
host="服務(wù)器地址",
user="root",
password="123456",
database="數(shù)據(jù)庫(kù)名",
charset="utf8mb4"
)
return conn
pymysql 入門(mén)實(shí)例
- 獲取連接對(duì)象
- 打開(kāi)
- 關(guān)閉
- 獲取游標(biāo)對(duì)象
- 執(zhí)行 SQL
- 查詢記錄
from . import get_conn
def test_demo():
# 1.獲取連接對(duì)象
conn = get_conn()
# 2.獲取游標(biāo)對(duì)象
cursor = conn.cursor()
# 3.執(zhí)行SQL
cursor.execute("SELECT VERSION()")
# 4.查詢結(jié)果
version = cursor.fetchone()
print(f"數(shù)據(jù)庫(kù)的版本是:{version}")
# 5.關(guān)閉連接
conn.close()
pymysql 數(shù)據(jù)庫(kù)操作
- CRUD 操作
- 創(chuàng)建表
- 插入記錄
- 查詢記錄
- 更新記錄
- 刪除記錄
- 執(zhí)行事務(wù)
- 提交:commit
- 回滾:rollback
pymysql 創(chuàng)建表
- 創(chuàng)建表
testcase
from . import get_conn
def test_create():
conn = get_conn() # 獲取連接
cursor = conn.cursor() # 獲取游標(biāo)
sql = """
CREATE TABLE `testcase` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_bin NOT NULL,
`expect` varchar(255) COLLATE utf8_bin NOT NULL,
`owner` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
"""
cursor.execute(sql) # 執(zhí)行SQL
conn.close() # 關(guān)閉連接
pymysql 插入操作
- 插入記錄
from . import get_conn
def test_insert():
conn = get_conn() # 獲取連接
cursor = conn.cursor() # 獲取游標(biāo)
sql = """INSERT INTO testcase
(id, title, expect, owner)
values (1, 'S11總決賽', '冠軍', 'EDG');
"""
cursor.execute(sql) # 執(zhí)行SQL
conn.commit() # 提交
執(zhí)行事務(wù)
- 提交操作:
commit()
- 回滾操作:
rollback()
try-catch-finally
from . import get_conn
def test_insert():
conn = get_conn() # 獲取連接
cursor = conn.cursor() # 獲取游標(biāo)
sql = """INSERT INTO testcase
(id, title, expect, owner)
values (2, 'S11全球總決賽', '冠軍', 'EDG');
"""
try:
cursor.execute(sql) # 執(zhí)行SQL
conn.commit() # 提交事務(wù)
except:
conn.rollback() # 回滾事務(wù)
finally:
conn.close() # 關(guān)閉連接
pymysql 查詢操作
- 查詢操作
-
fetchone()
:獲取單條記錄 -
fetchmany(n)
:獲取 n 條記錄 -
fetchall()
:獲取所有結(jié)果記錄
-
import sys
from . import get_conn
def test_retrieve():
conn = get_conn() # 獲取連接
cursor = conn.cursor() # 獲取游標(biāo)
sql = "SELECT * FROM testcase;"
# 捕獲異常
try:
cursor.execute(sql) # 執(zhí)行SQL
record = cursor.fetchone() # 查詢記錄
print(record)
except Exception as e:
print(sys.exc_info()) # 打印錯(cuò)誤信息
finally:
conn.close() # 關(guān)閉連接
pymysql 更新操作
- 更新數(shù)據(jù)表的數(shù)據(jù)
from . import get_conn
def test_update():
conn = get_conn()
cursor = conn.cursor()
sql = "UPDATE testcase SET owner='hogwarts' WHERE id=2;"
try:
cursor.execute(sql) # 執(zhí)行SQL
conn.commit() # 提交事務(wù)
except:
conn.rollback() # 回滾事務(wù)
finally:
conn.close() # 關(guān)閉連接
pymysql 刪除操作
- 刪除數(shù)據(jù)表的數(shù)據(jù)
from . import get_conn
def test_delete():
conn = get_conn() # 獲取連接
cursor = conn.cursor() # 獲取游標(biāo)
sql = "DELETE FROM testcase WHERE id=3;"
try:
cursor.execute(sql) # 執(zhí)行SQL
conn.commit() # 提交事務(wù)
except:
conn.rollback() # 回滾事務(wù)
finally:
conn.close() # 關(guān)閉連接
五僻族、常用第三方庫(kù)urllib3
1、urllib3 概述
-
內(nèi)置模塊
- urllib
-
第三方庫(kù)
requests
urllib3
- 線程安全
- 連接池管理
- 客戶端 SSL/TLS 驗(yàn)證
- 支持 HTTP 和 SOCKS 代理
官方文檔:https://urllib3.readthedocs.io/en/stable/
2屡谐、urllib3 安裝
- 通過(guò) pip 安裝
pip install urllib3
3述么、urllib3 發(fā)送 HTTP 請(qǐng)求
- 導(dǎo)入
urllib3
模塊 - 創(chuàng)建
PoolManager
實(shí)例 - 調(diào)用
request()
方法
import urllib3
def test_HTTP():
# 創(chuàng)建連接池對(duì)象,默認(rèn)會(huì)校驗(yàn)證書(shū)
pm = urllib3.PoolManager()
# 發(fā)送HTTP請(qǐng)求
res = pm.request(method='GET', url="http://httpbin.org/robots.txt")
print(type(res))
3.1 urllib3 HTTPResponse 對(duì)象
- status 屬性
- headers 屬性
- data 屬性
import urllib3
def test_response():
# 創(chuàng)建連接池對(duì)象
pm = urllib3.PoolManager()
# 發(fā)送請(qǐng)求
resp = pm.request(method='GET', url="http://httpbin.org/ip")
print(resp.status) # 查看響應(yīng)狀態(tài)狀態(tài)碼
print(resp.headers) # 查看響應(yīng)頭信息
print(resp.data) # 查看響應(yīng)原始二進(jìn)制信息
3.2 urllib3 解析響應(yīng)內(nèi)容
二進(jìn)制響應(yīng)內(nèi)容解碼
JSON 字符串
import urllib3
import json
def test_response():
pm = urllib3.PoolManager()
resp = pm.request(method='GET', url="http://httpbin.org/ip")
# 獲取二進(jìn)制形式的響應(yīng)內(nèi)容
raw = resp.data
print(type(raw), raw)
# 使用utf-8解碼成字符串
content = raw.decode('utf-8')
print(type(content), content)
# 將JSON字符串解析成字典對(duì)象
dict_obj = json.loads(content)
print(type(dict_obj), dict_obj)
print(dict_obj['origin'])
4愕掏、urllib3 request 請(qǐng)求參數(shù)
- 語(yǔ)法:
request(method, url, fields, headers, **)
- 必填
-
method
:請(qǐng)求方式 -
url
:請(qǐng)求地址
-
- 選填
-
headers
:請(qǐng)求頭信息 -
fields
:請(qǐng)求體數(shù)據(jù) -
body
:指定請(qǐng)求體類型 -
tiemout
:設(shè)置超時(shí)時(shí)間
-
5度秘、urllib3 定制請(qǐng)求數(shù)據(jù)
- 定制請(qǐng)求頭信息
5.1使用 headers
參數(shù)
import urllib3
import json
def test_headers():
pm = urllib3.PoolManager()
url = "http://httpbin.org/get"
# 定制請(qǐng)求頭
headers = {'School': 'hogwarts'}
resp = pm.request('GET', url, headers=headers)
5.2定制查詢字符串參數(shù)
* fields
參數(shù):適用于GET, HEAD, DELETE
請(qǐng)求
* 拼接url
:適用于POST, PUT
請(qǐng)求
import urllib3
import json
# GET/HEAD/DELETE 請(qǐng)求
def test_fields():
pm = urllib3.PoolManager()
url = "http://httpbin.org/get"
fields = {'school': 'hogwarts'}
resp = pm.request(method='GET', url=url, fields=fields)
# POST/PUT 請(qǐng)求
def test_urlencode():
# 從內(nèi)置庫(kù)urllib的parse模塊導(dǎo)入編碼方法
from urllib.parse import urlencode
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
# POST和PUT請(qǐng)求需要編碼后拼接到URL中
encoded_str = urlencode({'school': 'hogwarts'})
resp = pm.request('POST', url=url+"?"+encoded_str)
5.4提交 form 表單數(shù)據(jù)
類型
'Content-Type': 'multipart/form-data
請(qǐng)求方式:POST、PUT
import urllib3
import json
# POST/PUT 請(qǐng)求
def test_form():
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
fields = {'school': 'hogwarts'}
# fields數(shù)據(jù)會(huì)自動(dòng)轉(zhuǎn)成form格式提交
resp = pm.request('POST', url, fields=fields)
5.5提交 JSON 格式數(shù)據(jù)
類型:
'Content-Type': 'application/json'
請(qǐng)求方式:POST饵撑、PUT
import urllib3
import json
def test_json():
pm = urllib3.PoolManager()
url = "http://httpbin.org/post"
# 設(shè)定請(qǐng)求體數(shù)據(jù)類型
headers={'Content-Type': 'application/json'}
# JSON文本數(shù)據(jù)
json_str = json.dumps({'school': 'hogwarts'})
resp = pm.request('POST', url, headers=headers, body=json_str)
5.6timeout
:設(shè)置超時(shí)時(shí)間
時(shí)間單位:秒
值的格式:float 類型
import urllib3
def test_timeout():
pm = urllib3.PoolManager()
# 訪問(wèn)這個(gè)地址剑梳,服務(wù)器會(huì)在3秒后響應(yīng)
url = "http://httpbin.org/delay/3"
# 設(shè)置超時(shí)時(shí)長(zhǎng)
resp = pm.request(method='GET', url=url, timeout=4.0)
assert resp.status == 200
6唆貌、urllib3 發(fā)送 HTTPS 請(qǐng)求
HTTPS 請(qǐng)求默認(rèn)需要校驗(yàn)證書(shū)
-
PoolManager 的
cert_reqs
參數(shù)-
"CERT_REQUIRED"
:需要校驗(yàn) -
"CERT_NONE"
:取消校驗(yàn)
-
import urllib3
import json
def test_HTTPS():
# 創(chuàng)建不校驗(yàn)證書(shū)的連接池對(duì)象
pm_https = urllib3.PoolManager(cert_reqs="CERT_NONE")
url = "https://httpbin.ceshiren.com/get"
# 發(fā)送HTTPS請(qǐng)求
resp = pm_https.request(method='GET', url=url)
print(json.dumps(resp.data.decode('utf-8')))