学习日记-20190604

Flask 中模块导入的问题、Github API、Requests API测试形式

Flask 中模块导入的问题

如果另外建一个文件models.py

1
2
3
4
5
6
7
8
9
#models.py
from models import User,Post
# 则会报错,无法导入
# 这是因为Python会去读整个models脚本
from flaskblog import db
...
if __name__ == '__main__':
app.run(debug=True)
# 所以实质上是db导入失败

Flask 的一个扩展,用于密码hash加密

1
2
3
4
5
6
7
8
9
10
11
pip install flask_bcrypt
>>> from flask_bcrypt import Bcrypt
>>> bcrypt = Bcrypt()
>>> bcrypt.generate_password_hash('testing')
b'$2b$12$Ag5DAxUT0RjqhNdFSu1wH.4nfMSm031BkIL49jziQ4mFjtvS9buym'

>>> hash_pw = bcrypt.generate_password_hash('testing').decode('utf-8')
>>> bcrypt.check_password_hash(hash_pw,'password')
False
>>> bcrypt.check_password_hash(hash_pw,'testing')
True

Github API

【来源】https://segmentfault.com/a/1190000015144126

GET

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
# 访问用户信息
"user_url": "https://api.github.com/users/{user}"
# 个人所有repo
https://api.github.com/users/用户名/repos
# repo详细信息
https://api.github.com/repos/用户名/仓库名
# 获取某个repo的内容列表
https://api.github.com/repos/{user}/{repo}/contents
# 获取repo中子目录的内容列表
https://api.github.com/repos/{user}/gists/contents/目录名
# 获取repo中某文件信息(不包括内容)
https://api.github.com/repos/{user}/gists/contents/文件路径
# 获取某文件的原始内容(Raw)
https://raw.githubusercontent.com/用户名/仓库名/分支名/文件路径
# repo中所有的commits列表
https://api.github.com/repos/用户名/仓库名/commits
# 某一条commit详情
https://api.github.com/repos/用户名/仓库名/commits/某一条commit的SHA
# issues列表
https://api.github.com/repos/用户名/仓库名/issues
# 某条issue详情
https://api.github.com/repos/用户名/仓库名/issues/序号(issues都是以1,2,3这样的序列排号的)
# 某issue中的comments列表
https://api.github.com/repos/用户名/仓库名/issues/序号/comments
# 某comment详情
https://api.github.com/repos/用户名/仓库名/issues/comments/评论详情的ID评论ID是从issues列表中获得

POST

  • 分页功能。格式是?page=页数&per_page=每页包含数量
  • issues状态。格式是?state=状态

用户权限认证 采用OAuth2 token

PUT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 创建新文件
https://api.github.com/repos/用户名/仓库名/contents/文件路径
JSON格式
{
"message": "commit from INSOMNIA",
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}
必须添加权限验证(上面有写) 2. 数据传送格式选择JSON 3. 文件内容必须是把文件整体转为Base64字符串再存到JSON变量中 4. 文件路径中如果有不存在的文件夹,则会自动创建
# 更新文件
https://api.github.com/repos/用户名/仓库名/contents/文件路径
JSON格式
{
"message": "update from INSOMNIA",
"content": "Y3JlYXRlIGZpbGUgZnJvbSBJTlNPTU5JQQoKSXQncyB1cGRhdGVkISEhCgpJdCdzIHVwZGF0ZWQgYWdhaW4hIQ==",
"sha": "57642f5283c98f6ffa75d65e2bf49d05042b4a6d"
}
必须指定该文件的SHA码,相当于文件的ID
获取方式:GET content获取文件信息 找到sha

DELETE

1
2
3
4
5
6
7
# 删除文件
https://api.github.com/repos/用户名/仓库名/contents/文件路径
JSON格式
{
"message": "delete a file",
"sha": "46d2b1f2ef54669a974165d0b37979e9adba1ab2"
}

增删改issues不用将内容专程Base64编码

Requests 身份认证

基本身份认证

1
2
3
4
5
6
>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>

>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>

然后在进行OAuth2.0认证的时候发现自己不会写代码,于是。。。

惊觉Postman有生成代码的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# copy过来,能省则省
import requests

url = "https://api.github.com"

headers = {
'co': "",
'Authorization': "Bearer *(你自己github生成的token)",
'User-Agent': "PostmanRuntime/7.13.0",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Host': "api.github.com",
'accept-encoding': "gzip, deflate",
'Connection': "keep-alive",
'cache-control': "no-cache"
}

response = requests.request("GET", url, headers=headers)

print(response.text)

简化版,看来可以用Postman指导写代码,嘻嘻

1
2
3
4
5
6
7
import requests
url = "https://api.github.com"
headers = {
'Authorization': "Bearer *",
}
response = requests.get(url, headers=headers)
print(response.text)

用两种方式获取用户repos

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# UI测试形式
from selenium import webdriver
import re

driver = webdriver.Chrome()
driver.get("https://github.com/zhengjiani?tab=repositories")
elems = driver.find_element_by_id("user-repositories-list")
elem=elems.find_elements_by_tag_name("a")
repos = []
for i in range(len(elem)):
repos.append(elem[i].text)
repos = [elem for elem in repos if elem != "1"]
print(repos)
driver.close()
# 结果
['zhengjiani.github.io', 'markdownImages', 'pyAlgorithm', 'gitment-comments', 'microblog', 'WebTest', 'PythonPracticeImpl', 'Store', 'J2EE', 'Blog', 'cifaAnaly', 'nodejsPractise', 'JsoupLearn']

Requests API测试形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""查询用户,获取该用户所有的repos"""
import json
def get_repos_list():
import requests
response = requests.get("https://api.github.com/users/zhengjiani/repos")
r_dict=response.json()
repos = []
for i in range(len(r_dict)):
repos.append(r_dict[i]['full_name'])
print(repos)
if __name__ == "__main__":
get_repos_list()

# 结果
['zhengjiani/Blog', 'zhengjiani/cifaAnaly', 'zhengjiani/gitment-comments', 'zhengjiani/J2EE', 'zhengjiani/JsoupLearn', 'zhengjiani/markdownImages', 'zhengjiani/microblog', 'zhengjiani/nodejsPractise', 'zhengjiani/pyAlgorithm', 'zhengjiani/PythonPracticeImpl', 'zhengjiani/Store', 'zhengjiani/WebTest', 'zhengjiani/zhengjiani.github.io']

可以看出这种获取用API形式更方便,作为UI测试的断言补充。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"""查询用户,获取该用户所有的repos"""
import json
class GetRepoPage():
@staticmethod
def get_repos_list():
import requests
response = requests.get("https://api.github.com/users/zhengjiani/repos")
r_dict=response.json()
repos = []
for i in range(len(r_dict)):
repos.append(r_dict[i]['full_name'])
return repos
if __name__ == "__main__":
print(GetRepoPage.get_repos_list())