python随便写点东西.
类(class)是type的实例
实例(instance)是class的实例
isalnum() 判断下面的任意一个成立.
c.isalpha()可以判断汉字,其他国家的uincode可表示的字估计也可以.
c.isdecimal() 基本用来判断数字
c.isdigit()同上但是范围可能大一点.
c.isnumeric()可以判断uincode字符是否表示为数字的意思.
连接
标准库uu 是一个将任意二进制文件转化为文本的库,
主要使用uu.encode()
和uu.decode()
标准库path将输入的字符转化文路径对象然后进行各种操作的库
例如:p = Path('~/some.txt')
表示home下的some.txt文件路径,然后调用p.<somemethod>
就OK
open()的方法有四种, ‘r’ 读, ‘w’ 写, 'a’追加, 'x’独占(意思是不打开已有的文件)
打开的文件需要注意seek(offset[, whence])位移, turncate([size])截取, tell()报告位置.read, write就不说了.
从列表中删除元素的最佳法则应当是排序后从后往前删除.参考如下的代码.
if mylist:
mylist.sort()
last = mylist[-1]
for i in range(len(mylist)-2, -1, -1):
if last == mylist[i]:
del mylist[i]
else:
last = mylist[i]
Flask
手动创建的上下文, app.app_context(), app上下文, app.test_request_context()测试请求上下文
teardown_appcontext
弹出上下问时调用, 防止在程序内部有错误的情况下不调用after_request
保证程序在请求之后总是调用被teardown_appcontext注册的函数调用。
app_context
应用上下文
可使用with app.app_context():
激活上下文,
使用conetxt = app.app_context()
context.push
激活上下文, 使用context.pop()
销毁上下文
test_request_context
请求上下文
使用with app.test_request_context('/')
激活请求上下文.
使用context = app.test_request_context()
conetxt.push
激活上下文
使用test_request_context时app_context也会被激活.
test_client
使用 client=app.test_client()
创建测试客户端, client.get('/')
or client.post('/')
等发送测试请求.
json
flask中的json支持dataclasses, 给一个dataclass的示例:
@dataclass
class InventoryItem:
'''Class for keeping track of an item in inventory.'''
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
urllib中的一些操作.
urllib.parse中的parse_qsl, urlencode:
parse_qs可以将query_stirng解析为字典, parse_qsl 为元组, qs可以分解多个对应值, qsl只分解为单个值.
urlencode 将url编码, 一个很大的用处是将字典编辑为query_string.
urlopen()打开网站的东西.可以以后分析以下.
使用unittest测试
使用unittest测试时, 对于有上下文的环境, 先使用db.create_all(), 再弹出上下文, 否则会报错.
unittest中的assert类型:
Method | Checks that |
---|---|
assertEqual(a, b) | a == b |
assertNotEqual(a, b) | a != b |
assertTrue(x) | bool(x) is True |
assertFalse(x) | bool(x) is False |
assertIs(a, b) | a is b |
assertIsNot(a, b) | a is not b |
assertIsNone(x) | x is None |
assertIsNotNone(x) | x is not None |
assertIn(a, b) | a in b |
assertNotIn(a, b) | a not in b |
assertIsInstance(a, b) | isinstance(a, b) |
assertNotIsInstance(a, b) | not isinstance(a, b) |
assertRaises(exc, fun, *args, **kwds) | fun(*args, **kwds) raises exc |
assertRaisesRegex(exc, r, fun, *args, **kwds) | fun(*args, **kwds) raises exc and the message matches regex r |
assertWarns(warn, fun, *args, **kwds) | fun(*args, **kwds) raises warn |
assertWarnsRegex(warn, r, fun, *args, **kwds) | fun(*args, **kwds) raises warn and the message matches regex r |
assertLogs(logger, level) | The with block logs on logger with minimum level |
assertAlmostEqual(a, b) | round(a-b, 7) == 0 |
assertNotAlmostEqual(a, b) | round(a-b, 7) != 0 |
assertGreater(a, b) | a > b |
assertGreaterEqual(a, b) | a >= b |
assertLess(a, b) | a < b |
assertLessEqual(a, b) | a <= b |
assertRegex(s, r) | r.search(s) |
assertNotRegex(s, r) | not r.search(s) |
assertCountEqual(a, b) | a and b have the same elements in the same number, regardless of their order. |
imghdr
imghdr.what(filename, f)
只能判断文件, 鸡肋
Werkzeug
def _get_current_object(self):
"""返回当前对象. 这很有用, 如果出于性能的需求或者想要将真实
的对象传递到不同的上下文而需要获得代理背后的真实的对象.
"""
if not hasattr(self.__local, "__release_local__"):
return self.__local()
try:
return getattr(self.__local, self.__name__)
except AttributeError:
raise RuntimeError("no object bound to %s" % self.__name__)
LocalProxy可以直接代理Local或LocalStack, 也可以代理获取真正对象的函数, __release__local__
是只有Local和LocalStack才有的属性.
LocalProxy只能代理Local的一个属性.
例如:
>>> l = Local()
>>> l.name='zhangsan'
>>> lp = l('name')
>>> lp
'zhangsan'
>>> lp = LocalProxy(l, 'name')
>>> lp
'zhangsan'
def get_lcoal():
return l
lp = LocalProxy(get_local)
lp
返回的是local对象.
flask_login
- 只有调用
current_user
时才会从_request_ctx_stack.top
获取user, 调用login_manager
的_load_user
, 也就是从session中获取用户user_id然后从数据库中获取用户信息. - 记住密码从
session['remember']
获取, 如果选择记住密码, 会在每次请求之后在cookie中设置一个时长可选默认一年的cookie值, 在重新登陆后从cookie中获取这个值重新登陆. - session中保存的是user_id这个值是从user属性的get_id获取, 可以修改只需保持唯一即可.
mysqlclient的安装
sudo ln -s /usr/lib/x86_64-linux-gnu/libssl.so.1.1 /usr/lib64/libssl.so
sudo ln -s /usr/lib/x86_64-linux-gnu/libcrypto.so.1.1 /usr/lib64/libcrypto.so
注意适用于Ubuntu1904.