- 👋 Hi, I’m Valuebai, A Full-Stack Developer, Devops
- 👀 I’m interested in Web3
- 💞️ I’m looking to collaborate on Web3
- 📫 How to reach me: [email protected]
💪 Code with
🧰 Use Tools
🌱 Plan&Learning:
Python十分钟入门指南/技术图谱,持续更新收集整理中,期待你的参与
License: MIT License
💪 Code with
🧰 Use Tools
🌱 Plan&Learning:
if request.method == 'POST':
报错
return None
一般是请求路由URL中少了/,比如
/mail/send ——报错❌
/mail/send/ ——正常✔️
简易Web Server
你是否想过通过网络快速共享文件?好消息,Python为你提供了这样的功能。进入到你要共享文件的目录下并在命令行中运行下面的代码:
python2:
python -m SimpleHTTPServer 6666 ——这个命令是python2的
python3:
python -m http.server ——这个命令是python3才有的,在centOS执行会报错:/usr/bin/python: No module named http.server
[
'赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋',
'沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏',
'陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭',
'郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '任', '袁', '柳', '鲍', '史', '唐', '费', '薛',
'雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '安', '常', '傅', '卞', '齐', '元', '顾', '孟',
'平', '黄', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '狄', '米', '伏', '成', '戴', '谈',
'宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闵', '季', '贾',
'路', '娄', '江', '童', '颜', '郭', '梅', '盛', '林', '钟', '徐', '邱', '骆', '高', '夏', '蔡', '田',
'樊', '胡', '凌', '霍', '虞', '万', '支', '柯', '管', '卢', '莫', '柯', '房', '裘', '缪', '解', '应',
'宗', '丁', '宣', '邓', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '龚', '程', '嵇', '邢',
'裴', '陆', '荣', '翁', '荀', '于', '惠', '甄', '曲', '封', '储', '仲', '伊', '宁', '仇', '甘', '武',
'符', '刘', '景', '詹', '龙', '叶', '幸', '司', '黎', '溥', '印', '怀', '蒲', '邰', '从', '索', '赖',
'卓', '屠', '池', '乔', '胥', '闻', '莘', '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵',
'冉', '宰', '雍', '桑', '寿', '通', '燕', '浦', '尚', '农', '温', '别', '庄', '晏', '柴', '瞿', '阎',
'连', '习', '容', '向', '古', '易', '廖', '庾', '终', '步', '都', '耿', '满', '弘', '匡', '国', '文',
'寇', '广', '禄', '阙', '东', '欧', '利', '师', '巩', '聂', '关', '荆', '司马', '上官', '欧阳', '夏侯',
'诸葛', '闻人', '东方', '赫连', '皇甫', '尉迟', '公羊', '澹台', '公冶', '宗政', '濮阳', '淳于', '单于',
'太叔', '申屠', '公孙', '仲孙', '轩辕', '令狐', '徐离', '宇文', '长孙', '慕容', '司徒', '司空'];
重点,重点!!!----》要使用某个类的方法,需要先实例化一个对象再调用方法。
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
下面是两个装饰器函数的区别:
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
【git设置】
1、 每个项目需要在单独在.git里面的config文件添加下面的代码,设置不同的提交人信息,避免多个账户混乱
[user]
name = luhuibo
email = [email protected]
含义:主要用于系统路径中的分隔符
Windows系统通过是“\”,Linux类系统如Ubuntu的分隔符是“/”,而苹果Mac OS系统中是“:”。
再结合f-string格式打印
import os, sys
sep = os.sep
root_path = os.path.abspath(os.path.join(__file__, f"..{sep}..{sep}output{sep}log{sep}"))
sys.path.append(root_path)
print(root_path)
【python2转python3】在PyCharm的菜单栏中配置Python2代码转换Python3的工具
https://www.jianshu.com/p/abbb005ba002
1、【配置】代码模板,个人信息
File -> Settings -> Editor -> File and Codes Templates -> Python Script
我的设置
【版本1】
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : ${DATE}
# @Author : https://github.com/Valuebai/
"""
---------------------------------------------
Description:
Usage Example:
Change Activity:
---------------------------------------------
"""
def main():
"""test函数"""
print('test')
if __name__ == "__main__":
main()
【版本2】
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : ${DATE}
# @Author : https://github.com/Valuebai/
# @Desc :
def main():
"""main func"""
print('main')
if __name__ == "__main__":
main()
【版本3】
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Time : ${DATE}
@Author : https://github.com/Valuebai/
@描述说明 :
"""
__author__ = 'Valuebai'
def test():
"""test函数"""
print('test')
if __name__ == "__main__":
test()
2、【工具】Pylint 和 autoPep8
3、查看:这个类或者函数的代码逻辑感兴趣,也可以使用快速预览的方式在当前页面展示源代码
4、TO DO事项
5、格式化美化代码
5、多行标签页,一览无余
打开的文件越来越多,多到一行标签都装不下,装不下的标签页 PyCharm 会将其隐藏起来,并以数字的形式告诉你隐藏了几个文件,可以用下面的解决:
File -> Settings -> Editor -> General -> Editor Tabs
关闭show tabs in one row
4、设置Tab转空格
File -> Settings -> Editor -> Code Style > Python-> Tabs and indents=4
5、显示空格(可选)
6、调整代码字体大小
7、智能补全,忽略大小写
当你的对象是以大写字母开头时,而你使用小写字母编写代码时,是不能查找到该函数的,你必须得先切换成大写再输入一遍。
8、Jinjia模板语言设置(Jinjia代码注释高亮)
9、渲染模板时Pycharm有警告提示:模板文件找不到
File -> Settings -> Project: [你的项目名称] -> Project Structure
-> Appearance -> Show whitespaces
pip install pip -U
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
There are comments that keeping spamming crypto ads.
使用git提交代码时,不要将多余的代码提交,类似
def pd_excel_to_list(file_name):
"""
用pandas读取excel文件,结合numpy将数据转为list
:param file_name: 传入文件的路径
:return: [[], [] ,[]], 类似[['列1', '列2', '列3'], ['2行.1', '2行.2', '2行.3'], ['3行.1', '3行.2', '3行.3']]
"""
df = pd.read_excel(file_name, index=True, header=None)
df = df.fillna('') # 将表格的nan填充为''
np_data = np.array(df) # pd.values.tolist()只能转换到值,用np将所有的tolist
data_list = np_data.tolist()
return data_list
def pd_excel_to_list_of_dict(path):
"""
将excel表格的数据转为字典
- 第一行作为key
- 第二行与key对应的值作为value
- 直到N行,没有数据
:param path: excel 表格的路径
:return: 类似[{'列1': '2行.1', '列2': '2行.2', '列3': '2行.3'}, {'列1': '3行.1', '列2': '3行.2', '列3': '3行.3'}]
"""
# 读取Excel文件,默认读取第一个sheet
df = pd.read_excel(path)
# 替换Excel表格内的空单元格,否则在下一步处理中将会报错
df.fillna("")
# 调用pd_excel函数,读取的数据转为list
d_list = pd_excel_to_list(path)
# for循环,将表格数据转为字典
df_list = []
for i in df.index.values:
# loc为按列名索引,iloc为按位置索引,使用的是 [[行号], [列名]]
df_line = df.loc[i, d_list[0]].to_dict() # d_list[0]填入的是第一列的key
# 将每一行转换成字典后添加到列表
df_list.append(df_line)
return df_list
【官网】https://github.com/joke2k/faker
【具体使用】https://www.cnblogs.com/progor/p/9188683.html
from faker import Faker
# fake=Faker() #默认生成美国英文数据
fake=Faker(locale='zh_CN')
(.+)默认是贪婪匹配
(.+?)为惰性匹配
疑问号让.+的搜索模式从贪婪模式变成惰性模式。
var str = 'aaa
<.+?>会匹配
<.+>会匹配
要在浏览器测试结果的话,输入:
var str = 'aaa
str.match(/<.+?>/);
str.match(/<.+>/);
下面举个简单的例子来说明。
1.贪婪匹配是先看整个字符串是否匹配,如果不匹配,它会去掉字符串的最后一个字符,并再次尝试。如果还不匹配,那么再去掉当前最后一个,直到发现匹配或不剩任何字符。
var str='abcdabceba'
/.+b/ //匹配一个或多个任意字符后面跟一个字母b
执行str.match(/.+b/)
第一次(先看整个字符串是否是一个匹配) abcdabceba 不匹配,然后去掉最后一个字符a
第二次(去掉最后一个字符后再匹配) abcdabceb 匹配,返回abcdabceb。
2.惰性匹配是从左侧第一个字符开始向右匹配, 先看第一个字符是不是一个匹配, 如果不匹配就加入下一个字符再尝式匹配, 直到发现匹配...
执行str.match(/.+?b/)
第一次(读入左侧第一个字符) a 不匹配加一个再式
第二次 ab 匹配,返回ab
Python 日志模块 logging rotate 的坑儿:https://www.jianshu.com/p/25f70905ae9d
部署好用的命令,学起来
1、需要修改【python2版本】的这几个地方
第94行,将import StringIO修改成import io
第539行,将self.outputBuffer = StringIO.StringIO()修改成self.outputBuffer = io.StringIO()
第642行,将if not rmap.has_key(cls):修改成if not cls in rmap:
第766行,将uo = o.decode('latin-1')修改成uo = e
第775行,将ue = e.decode('latin-1')修改成ue = e
第631行,将print >> sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime)修改成print(sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime))
2、我将文件上传到这里备份
HTMLTestRunner.py【py3版本,使用删除后面的】.txt
3、测试代码
将上面的HTMLTestRunner.py 跟下面test.py放在同一目录下
1)安装selenium
2)将geckodriver.exe 文件下载,放到python安装目录:C:\Python36下
3)用命令行执行python test.py, 不然在pycharm里面总是报ok的那种
# -*- coding: utf-8 -*-
from selenium import webdriver
from HTMLTestRunner import HTMLTestRunner # 导入HTMLTestRunner模块
import unittest, time
class BaiduIdeTest(unittest.TestCase):
# 三引号表示doc string类型注释,用来描述函数、类和方法
'''baidu search testing'''
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.baidu.com/"
def test_baidu_ide(self):
'''Search Keyword'''
driver = self.driver
driver.get(self.base_url)
driver.find_element_by_id("kw").clear()
driver.find_element_by_id("kw").send_keys("HTMLTestRunner")
driver.find_element_by_id("su").click()
time.sleep(5)
self.assertEqual(u"HTMLTestRunner_百度搜索", driver.title)
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
# 构造测试套件
testsuit = unittest.TestSuite()
testsuit.addTest(BaiduIdeTest("test_baidu_ide"))
# 按照一定格式获取当前时间,%Y表示带世纪的年(2019),%y表示不带世纪的年(19),time.strftime()表示获得当前时间并格式化字符串
now = time.strftime("%Y%m%d_%H%M%S")
# 将当前时间加入到报告文件名称中
filename = './' + now + 'result.html'
# 定义测试报告存放路径,通过open()方法以二进制写模式('wb')打开当前目录下的result.heml,如果没有,则自动创建。
fp = open('./result.html', 'wb')
# 定义测试报告,调用HTMLTestRunner模块下的HTMLTestRunner类,stream 指定测试报告文件,title 定义测试报告的标题,description 定义测试报告的副标题
runner = HTMLTestRunner(stream=fp, title='自动化测试报告', description='用例执行情况:')
# 通过HTMLTestRunner的run()方法来运行测试套件中的测试用例
runner.run(testsuit)
# 关闭测试报告
fp.close()
print('11111111')
【知乎规范】强烈推荐:编码之前碎碎念(工程实践)https://python-web-guide.readthedocs.io/zh/latest/codingstyle/codingstyle.html
【Python Code Style】https://docs.python-guide.org/writing/style/
【Python最佳实践指南!】https://pythonguidecn.readthedocs.io/zh/latest/
Python官方有一个PEP8:Style Guide for Python Code。https://www.python.org/dev/peps/pep-0008/ 采用一致的代码风格,有利于项目的多人协作和后续的修改维护工作。Brett Slatkin写的《Effective Python》的第2条列举了一些PEP8中绝对应该遵守的规则。列举其中的一些(语言表述上和内容上我略有修改,是直接从我自己的笔记中复制出来):
【规范】单元测试放在根目录下的tests
# 通用的单元测试框架
class TestFrame(unittest.TestCase):
def setUp(self):
"""每次执行用例前都执行"""
pass
def test_AAA(self):
pass
def test_BBB(self):
pass
def tearDown(self):
"""每次执行用例后都执行"""
pass
解决方案:在run_test.py文件最前面加上以下代码,必须放在所有improt之前!!!!!
import sys
import os
curPath = os.path.abspath(os.path.dirname(file))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.