(六)python環(huán)境管理及三方庫

一、venv環(huán)境管理

1、 venv 虛擬環(huán)境的優(yōu)點(diǎn)

  • 獨(dú)立的 Python 環(huán)境,不會產(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
  • 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 版本開始自帶
    • python3 的 3.4 版本開始自帶
  • https://pypi.org/ 托管了大量流行的 Python 包

pip 常用命令

功能 指令
查看 pip 版本 pip -V
查看幫助文檔 pip help
查看包列表 pip list
導(dǎo)出包列表 pip freeze
安裝 pip install 包名
升級 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 升級包

  • 升級已安裝的 Python 包
$ pip install -U pytest

pip 卸載包

  • 卸載 Python 包
# 卸載包

$ pip uninstall pytest

pip 使用鏡像加速

三、常用第三方庫yaml

1、YAML

  • 一種數(shù)據(jù)序列化格式
  • 用于人類的可讀性和與腳本語言的交互
  • 一種被認(rèn)為可以超越 XML、JSON 的配置文件

2、YAML 基本語法規(guī)則

  • 大小寫敏感
  • 使用縮進(jìn)表示層級關(guān)系
  • 縮進(jìn)時(shí)不允許使用 Tab 鍵,只允許使用空格
  • 縮進(jìn)的空格數(shù)目不重要,只要相同層級的元素左側(cè)對齊即可
  • # 表示注釋,從這個(gè)字符一直到行尾,都會被解析器忽略

3、YAML 支持的數(shù)據(jù)結(jié)構(gòu)

  • 對象:鍵值對的集合,用冒號 “:” 表示
  • 數(shù)組:一組按次序排列的值,前加 “-”
  • 純量:單個(gè)的、不可再分的值
    • 字符串
    • 布爾值
    • 整數(shù)
    • 浮點(diǎn)數(shù)
    • Null
    • 時(shí)間
    • 日期
# 編程語言
languages:
  - PHP
  - Java
  - Python 
book:
  Python入門: # 書籍名稱
    price: 55.5
    author: Lily
    available: True
    repertory: 20
    date: 2018-02-17
  Java入門:
    price: 60
    author: Lily
    available: False
    repertory: Null
    date: 2018-05-11

4、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 可以把對象轉(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)

四、常用第三方庫pymysql

1、pymysql 概述

  • Python 的數(shù)據(jù)庫接口標(biāo)準(zhǔn)是 Python DB-API

  • PyMySQL 是從 Python 連接到 MySQL 數(shù)據(jù)庫服務(wù)器的接口

  • PyMySQL 的目標(biāo)是成為 MySQLdb 的替代品

  • 官方文檔:http://pymysql.readthedocs.io/

2、pymysql 安裝

  • 使用 pip 安裝
  • 使用 Pycharm 界面安裝
pip install pymysql

3、pymysql 連接數(shù)據(jù)庫

  • host:MySQL 服務(wù)器地址
  • user:用戶名
  • password:密碼
  • database:數(shù)據(jù)庫名稱
  • charset:編碼方式,推薦使用 utf8mb4
# 1.導(dǎo)入庫
import pymysql

# 2.建立連接
conn = pymysql.connect(host='服務(wù)器地址',
                     user='用戶名',
                     password='密碼',
                     database='數(shù)據(jù)庫名',
                     charset="utf8mb4")
# 3.關(guān)閉連接
conn.close()

pymysql 連接數(shù)據(jù)庫

  • 封裝獲取連接的函數(shù)
import pymysql

# 1.封裝建立連接的對象
def get_conn():
    conn = pymysql.connect(
        host="服務(wù)器地址",
        user="root",
        password="123456",
        database="數(shù)據(jù)庫名",
        charset="utf8mb4"
    )

    return conn

pymysql 入門實(shí)例

  • 獲取連接對象
    • 打開
    • 關(guān)閉
  • 獲取游標(biāo)對象
    • 執(zhí)行 SQL
    • 查詢記錄
from . import get_conn

def test_demo():
    # 1.獲取連接對象
    conn = get_conn()
    # 2.獲取游標(biāo)對象
    cursor = conn.cursor()
    # 3.執(zhí)行SQL
    cursor.execute("SELECT VERSION()")
    # 4.查詢結(jié)果
    version = cursor.fetchone()
    print(f"數(shù)據(jù)庫的版本是:{version}")
    # 5.關(guān)閉連接
    conn.close()

pymysql 數(shù)據(jù)庫操作

  • 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)閉連接

五、常用第三方庫urllib3

1、urllib3 概述

  • 內(nèi)置模塊

    • urllib
  • 第三方庫

    • requests

    • urllib3

  • 線程安全
  • 連接池管理
  • 客戶端 SSL/TLS 驗(yàn)證
  • 支持 HTTP 和 SOCKS 代理

官方文檔:https://urllib3.readthedocs.io/en/stable/

2、urllib3 安裝

  • 通過 pip 安裝

pip install urllib3

3、urllib3 發(fā)送 HTTP 請求

  • 導(dǎo)入 urllib3 模塊
  • 創(chuàng)建 PoolManager 實(shí)例
  • 調(diào)用 request() 方法
import urllib3

def test_HTTP():
    # 創(chuàng)建連接池對象,默認(rèn)會校驗(yàn)證書
    pm = urllib3.PoolManager()
    # 發(fā)送HTTP請求
    res = pm.request(method='GET', url="http://httpbin.org/robots.txt")

    print(type(res))

3.1 urllib3 HTTPResponse 對象

  • status 屬性
  • headers 屬性
  • data 屬性
import urllib3

def test_response():
    # 創(chuàng)建連接池對象
    pm = urllib3.PoolManager()
    # 發(fā)送請求
    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字符串解析成字典對象
    dict_obj = json.loads(content)
    print(type(dict_obj), dict_obj)
    print(dict_obj['origin'])

4、urllib3 request 請求參數(shù)

  • 語法:request(method, url, fields, headers, **)
  • 必填
    • method:請求方式
    • url:請求地址
  • 選填
    • headers:請求頭信息
    • fields:請求體數(shù)據(jù)
    • body:指定請求體類型
    • tiemout:設(shè)置超時(shí)時(shí)間

5、urllib3 定制請求數(shù)據(jù)

  • 定制請求頭信息

5.1使用 headers 參數(shù)

import urllib3
import json

def test_headers():
    pm = urllib3.PoolManager()
    url = "http://httpbin.org/get"

    # 定制請求頭
    headers = {'School': 'hogwarts'}
    resp = pm.request('GET', url, headers=headers)

5.2定制查詢字符串參數(shù)
* fields 參數(shù):適用于GET, HEAD, DELETE 請求
* 拼接url:適用于POST, PUT請求

import urllib3
import json

# GET/HEAD/DELETE 請求
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 請求
def test_urlencode():
   # 從內(nèi)置庫urllib的parse模塊導(dǎo)入編碼方法
    from urllib.parse import urlencode
    pm = urllib3.PoolManager()
    url = "http://httpbin.org/post"
    # POST和PUT請求需要編碼后拼接到URL中
    encoded_str = urlencode({'school': 'hogwarts'})
    resp = pm.request('POST', url=url+"?"+encoded_str)

5.4提交 form 表單數(shù)據(jù)

  • 類型 'Content-Type': 'multipart/form-data

  • 請求方式:POST、PUT

import urllib3
import json

# POST/PUT 請求
def test_form():
    pm = urllib3.PoolManager()
    url = "http://httpbin.org/post"
    fields = {'school': 'hogwarts'}

    # fields數(shù)據(jù)會自動(dòng)轉(zhuǎn)成form格式提交
    resp = pm.request('POST', url, fields=fields)

5.5提交 JSON 格式數(shù)據(jù)

  • 類型:'Content-Type': 'application/json'

  • 請求方式:POST、PUT

import urllib3
import json

def test_json():
    pm = urllib3.PoolManager()
    url = "http://httpbin.org/post"

    # 設(shè)定請求體數(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()
    # 訪問這個(gè)地址,服務(wù)器會在3秒后響應(yīng)
    url = "http://httpbin.org/delay/3"

    # 設(shè)置超時(shí)時(shí)長
    resp = pm.request(method='GET', url=url, timeout=4.0)
    assert resp.status == 200

6、urllib3 發(fā)送 HTTPS 請求

  • HTTPS 請求默認(rèn)需要校驗(yàn)證書

  • PoolManager 的 cert_reqs 參數(shù)

    • "CERT_REQUIRED":需要校驗(yàn)
    • "CERT_NONE":取消校驗(yàn)
import urllib3
import json

def test_HTTPS():
    # 創(chuàng)建不校驗(yàn)證書的連接池對象
    pm_https = urllib3.PoolManager(cert_reqs="CERT_NONE")
    url = "https://httpbin.ceshiren.com/get"

    # 發(fā)送HTTPS請求
    resp = pm_https.request(method='GET', url=url)
    print(json.dumps(resp.data.decode('utf-8')))

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容