python 技术大杂烩

20230204

python升级报错
pip3 install -U pip
Could not fetch URL https://pypi.tuna.tsinghua.edu.cn/simple/pip/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping
Requirement already up-to-date: pip in /usr/local/lib/python3.6/site-packages
You are using pip version 9.0.1, however version 23.0 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

解决:
pip3 install --upgrade pip --trusted-host pypi.tuna.tsinghua.edu.cn

20221014

python django websocket配置
视频课程

  • 安装channel
  • 配置setting,1、apps channel 2、配置asgi.py
  • 新建asgi.py 引用routing ws路由配置
  • 新建routing.py 配置路由
[root@allin app]# cat app/asgi.py
# mysite/asgi.py
import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from webssh.routing import websocket_urlpatterns

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    ),
})
[root@allin app]# cat webssh/routing.py
from django.urls import re_path
#from webssh.tools import websocket
from webssh import consumers

websocket_urlpatterns = [
    #path('webssh/', websocket.WebSSH),
    re_path(r'ws/(?P<group>\w+)/$', consumers.ChatConsumer.as_asgi()),
    re_path(r'room/$', consumers.ChatConsumer.as_asgi()),
]

20221011

token 签名认证

import json
import base64
import time
import hashlib
import hmac
import requests
        secret = bytes(self.SECRET, "utf-8")
        hashString = bytes(hashStr, "utf-8")
        hash = hmac.new(secret, hashString, digestmod=hashlib.sha1).hexdigest()
        # hash = hmac.new(secret, hashString, digestmod=hashlib.sha1).digest()
        # hash = base64.b64encode(hash).decode("utf-8")

    def signature(self, method, uri, params):
        key = bytes(self.SECRET, "utf-8")
        msg = bytes(f"{method}\n"
                    f"{self.X_Hmac_Auth_Timestamp}\n"
                    f"{self.X_Hmac_Auth_Nonce}\n"
                    f"{uri}\n"
                    f"{unquote_plus(self.paramsort(params))}",
                    "utf-8")
        dig = hmac.new(key, msg, digestmod=hashlib.sha256).digest()
        out = base64.b64encode(dig).decode("utf-8")
        return out    
    def paramsort(params):
        result = []
        for k, v in parse_qsl(params):
            bisect.insort_right(result, (k, v))
        return urlencode(result)

20200514

列表切片 :开始,每隔几次
类表组合简写
a[1::2]

 a = [1,2,3,4,5]
 b = ['a','b','c','d','e']
str(i)+str(j) for i in a  for j in b]
['1a', '1b', '1c', '1d', '1e', '2a', '2b', '2c', '2d', '2e', '3a', '3b', '3c', '3d', '3e', '4a', '4b', '4c', '4d', '4e', '5a', '5b', '5c', '5d

20200423

字典排序
dic = {‘a’:31, ‘bc’:5, ‘c’:3, ‘asd’:4, ‘33’:56, ‘d’:0}
sorted(dic.items(),key=lambda x:x[1],reverse = True)

20200421

a = ‘2020-04-21’
’ '.join( map( str, map(int,a.split(“-”)) ) )
转换为
2020 4 21

20200224

sql 并列 and 重叠查询

关联查询并列
select 
    count(id) as use_total,
    '2019' as time,
    (select count(id)  from supt_order_review_analysis) as all_total  
from supt_order_review_analysis where supt_effort in (1,0)
union all
select 
    count(id) as use_total,
    '2020' as time,
    (select count(id)  from supt_order_review_analysis) as all_total  
from supt_order_review_analysis where supt_effort in (2,3,4,5)

20191125

        def errorFun(self):
                message = {}
                e_type, e_value, e_traceback = sys.exc_info()
                message['File'] = e_traceback.tb_frame.f_code.co_filename
                message['FunName'] = e_traceback.tb_frame.f_code.co_name
                message['Line']= e_traceback.tb_lineno
                message['content']= str(e_value)
                # out = {"code": 500, "mesg": message, "data": "error"}
                message = traceback.format_exc()
                out = {"code": 500, "mesg": message, "data": "error"}
                self.logger.error(out)
                # out = json.dumps(out, ensure_ascii=False, indent=4)
                print(out)
                return(out)

        def readJson(self,id):
            try:
                out = {"code": 500, "mesg": "", "data": ""}
                fileName = '%s/static/data/%s.json'%(BASE_DIR,id)
                with open(fileName, 'r') as f:
                    data = json.load(f)
                    # data = json.loads(f.read())
                    data = json.loads(data)
                    print(350,type(data))
                    out['code'] = 200
                    out['mesg'] = "读取json数据成功"
                    out['data'] = data
                    # print(type(out))
                    # print(337,type(out),type(f.read()),type(json.loads(out)))
                    return out
            except Exception as e:
                return self.errorFun()

        def saveJson(self,id,data):
            try:
                fileName = '%s/static/data/%s.json'%(BASE_DIR,id)
                # dataJson = json.dumps(data,ensure_ascii=False, indent=4)
                with open(fileName, 'w') as f:
                    # f.write(dataJson)
                    json.dump(data, f, ensure_ascii=False, indent=4)
                return True
            except Exception as e:
                return self.errorFun()

20191023

mysql 多条件查询 正则匹配
select id from project where id regexp’5|6|3’

20190924

import copy
深拷贝
wilber = copy.deepcopy(will)
浅拷贝 copy.copy(will) 只拷贝引用

20190826

生成随机字符串

import random
import string
test = ''.join(random.sample(string.ascii_letters + string.digits, 8))
20190806

out1 = re.findall(r’问题描述:(.*?)\n’,one[25],re.S|re.M)

20190722
os.sep    可以取代操作系统特定的路径分隔符。windows下为 '\\'
os.name    字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是 'posix'
os.getcwd()    函数得到当前工作目录,即当前Python脚本工作的目录路径
os.getenv()    获取一个环境变量,如果没有返回none
os.putenv(key, value)    设置一个环境变量值
os.listdir(path)    返回指定目录下的所有文件和目录名
os.remove(path)    函数用来删除一个文件
os.system(command)    函数用来运行shell命令
os.linesep    字符串给出当前平台使用的行终止符。例如,Windows使用 '\r\n',Linux使用 '\n' 而Mac使用 '\r'
os.path.split(path)        函数返回一个路径的目录名和文件名
os.path.isfile()    和os.path.isdir()函数分别检验给出的路径是一个文件还是目录
os.path.exists()    函数用来检验给出的路径是否真地存在
os.curdir        返回当前目录 ('.')
os.mkdir(path)    创建一个目录
os.makedirs(path)    递归的创建目录
os.chdir(dirname)    改变工作目录到dirname          
os.path.getsize(name)    获得文件大小,如果name是目录返回0L
os.path.abspath(name)    获得绝对路径
os.path.normpath(path)    规范path字符串形式
os.path.splitext()        分离文件名与扩展名
os.path.join(path,name)    连接目录与文件名或目录
os.path.basename(path)    返回文件名
os.path.dirname(path)    返回文件路径
os.walk(top,topdown=True,οnerrοr=None)        遍历迭代目录
os.rename(src, dst)        重命名file或者directory src到dst 如果dst是一个存在的directory, 将抛出OSError. 在Unix, 如果dst在存且是一个file, 如果用户有权限的话,它将被安静的替换. 操作将会失败在某些Unix 中如果src和dst在不同的文件系统中. 如果成功, 这命名操作将会是一个原子操作 (这是POSIX 需要). 在 Windows上, 如果dst已经存在, 将抛出OSError,即使它是一个文件. 在unix,Windows中有效。
os.renames(old, new)    递归重命名文件夹或者文件。像rename()

# shutil 模块

shutil.copyfile( src, dst)    从源src复制到dst中去。当然前提是目标地址是具备可写权限。抛出的异常信息为IOException. 如果当前的dst已存在的话就会被覆盖掉
shutil.move( src, dst)        移动文件或重命名
shutil.copymode( src, dst)    只是会复制其权限其他的东西是不会被复制的
shutil.copystat( src, dst)    复制权限、最后访问时间、最后修改时间
shutil.copy( src, dst)        复制一个文件到一个文件或一个目录
shutil.copy2( src, dst)        在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,类似于cp –p的东西
shutil.copy2( src, dst)        如果两个位置的文件系统是一样的话相当于是rename操作,只是改名;如果是不在相同的文件系统的话就是做move操作
shutil.copytree( olddir, newdir, True/Flase)
把olddir拷贝一份newdir,如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符号连接
shutil.rmtree( src )    递归删除一个目录以及目录内的所有内容
20190716

python 链接redis

import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
k = 'name'
out = 'haohao'
r.set(key,out) 
out = r.get(key)
out = json.loads(out)

获取所有已存key值
print(r.scan_iter())
for key in r.scan_iter(): 
    print(key)
 
列表key值
r.keys()
删除key值
r.delete("del1","del2")  
  
20190715
  1. 使用如下命令下载到2.6版本
    wget http://www.python.org/ftp/python/2.6/Python-2.6.tgz
    1
  2. 解压python
    tar xzf Python-2.6.tgz
    cd Python-2.6
    1
    2
  3. 编译安装python
    ./configure --prefix=/usr/local/python2.6
    make && make install
    1
    2
  4. 创建一个python的链接
    ln -sf /usr/local/python2.6/bin/python2.6 /usr/bin/python
20190711

python 执行函数

exec("print('Hello World')")
20190630

获取文件时间

time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getatime(file))) 访问
time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(file))) 修改
time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(file)))创建

20190626
----------自定义功能调用外部函数-----------
from functools import partial
>>> def foo(cooked, standard):
...     print "foo called with cooked: %s, standard: %s" % \
...               (cooked, standard)
cooked1 = partial(foo, 'cooked_value1')
cooked1('value1'
20190624

推理引擎 逻辑编程
pip install pyDatalog

>>> pyDatalog.create_terms('X,Y,Z,father,fatherOf,grandfatherOf')
>>> fatherOf['zhangsan']='lisi'
>>> fatherOf['lisi']='wangwu'
>>> print(grandfatherOf['zhangsan']==X)
X
------
wangwu
20190614

安装 mac notebooks

sudo pip install jupyter
报错
ERROR: matplotlib 1.3.1 requires nose, which is not installed.
ERROR: python-dateutil 2.8.0 has requirement six>=1.5, but you'll have six 1.4.1 which is incompatible.
ERROR: prompt-toolkit 1.0.16 has requirement six>=1.9.0, but you'll have six 1.4.1 which is incompatible.
ERROR: jsonschema 3.0.1 has requirement six>=1.11.0, but you'll have six 1.4.1 which is incompatible.
ERROR: bleach 3.1.0 has requirement six>=1.9.0, but you'll have six 1.4.1 which is incompatible.
Installing collected packages: pygments, ipython-genutils, enum34, decorator, traitlets, pyzmq, python-dateutil, futures, singledispatch, backports-abc, tornado, jupyter-core, jupyter-client, simplegeneric, backports.shutil-get-terminal-size, ptyprocess, pexpect, wcwidth, prompt-toolkit, scandir, pathlib2, pickleshare, appnope, ipython, ipykernel, qtconsole, Send2Trash, configparser, entrypoints, functools32, pyrsistent, attrs, jsonschema, nbformat, webencodings, bleach, MarkupSafe, jinja2, pandocfilters, defusedxml, testpath, mistune, nbconvert, terminado, ipaddress, prometheus-client, notebook, widgetsnbextension, ipywidgets, jupyter-console, jupyter
  Found existing installation: python-dateutil 1.5
    Uninstalling python-dateutil-1.5:
    
    pip install  python-dateutil==2.8.0
    报错 
    ERROR: Cannot uninstall 'six'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
20190528
import requests
url = 'www.baidu.com'
r  = requests.get(url)
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

上传文件
url = 'http://127.0.0.1/upload'
files = {'file': open('D:/test.apk', 'rb')}           
data = {'xxx':xxx,'xxx':xxx}
  
response = requests.post(url, files=files, data=data)
json = response.json()


20190410
	python 3  搭建简易http 下载文件
	python3 -m http.server
	python2 -m SmlpHttpServer
20190406

发送邮件qq 163

https://blog.csdn.net/weixin_42337937/article/details/88674001
2019-0329
python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。

得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()

返回指定目录下的所有文件和目录名:os.listdir()

函数用来删除一个文件:os.remove()

删除多个目录:os.removedirs(r“c:\python”)

检验给出的路径是否是一个文件:os.path.isfile()

检验给出的路径是否是一个目录:os.path.isdir()

判断是否是绝对路径:os.path.isabs()

检验给出的路径是否真地存:os.path.exists()

返回一个路径的目录名和文件名:os.path.split()     eg os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt') 

分离扩展名:os.path.splitext()

获取路径名:os.path.dirname()

获取文件名:os.path.basename()

运行shell命令: os.system()

读取和设置环境变量:os.getenv() 与os.putenv()

给出当前平台使用的行终止符:os.linesep    Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'

指示你正在使用的平台:os.name       对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'

重命名:os.rename(old, new)

创建多级目录:os.makedirs(r“c:\python\test”)

创建单个目录:os.mkdir(“test”)

获取文件属性:os.stat(file)

修改文件权限与时间戳:os.chmod(file)

终止当前进程:os.exit()

获取文件大小:os.path.getsize(filename)


文件操作:
os.mknod("test.txt")        创建空文件
fp = open("test.txt",w)     直接打开一个文件,如果文件不存在则创建文件

关于open 模式:

w     以写方式打开,
a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+     以读写模式打开
w+     以读写模式打开 (参见 w )
a+     以读写模式打开 (参见 a )
rb     以二进制读模式打开
wb     以二进制写模式打开 (参见 w )
ab     以二进制追加模式打开 (参见 a )
rb+    以二进制读写模式打开 (参见 r+ )
wb+    以二进制读写模式打开 (参见 w+ )
ab+    以二进制读写模式打开 (参见 a+ )

 

fp.read([size])                     #size为读取的长度,以byte为单位

fp.readline([size])                 #读一行,如果定义了size,有可能返回的只是一行的一部分

fp.readlines([size])                #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。

fp.write(str)                      #把str写到文件中,write()并不会在str后加上一个换行符

fp.writelines(seq)            #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。

fp.close()                        #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。  如果一个文件在关闭后还对其进行操作会产生ValueError

fp.flush()                                      #把缓冲区的内容写入硬盘

fp.fileno()                                      #返回一个长整型的”文件标签“

fp.isatty()                                      #文件是否是一个终端设备文件(unix系统中的)

fp.tell()                                         #返回文件操作标记的当前位置,以文件的开头为原点

fp.next()                                       #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。

fp.seek(offset[,whence])              #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。

fp.truncate([size])                       #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

 

目录操作:
os.mkdir("file")                   创建目录
复制文件:
shutil.copyfile("oldfile","newfile")       oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile")            oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
复制文件夹:
shutil.copytree("olddir","newdir")        olddir和newdir都只能是目录,且newdir必须不存在
重命名文件(目录)
os.rename("oldname","newname")       文件或目录都是使用这条命令
移动文件(目录)
shutil.move("oldpos","newpos")   
删除文件
os.remove("file")
删除目录
os.rmdir("dir")只能删除空目录
shutil.rmtree("dir")    空目录、有内容的目录都可以删
转换目录
os.chdir("path")   换路径

 

Python读写文件
1.open
使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。

file_object = open('thefile.txt')
try:
     all_the_text = file_object.read( )
finally:
     file_object.close( )

注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。

2.读文件
读文本文件
input = open('data', 'r')
#第二个参数默认为r
input = open('data')

 

读二进制文件
input = open('data', 'rb')
 

读取所有内容
file_object = open('thefile.txt')
try:
     all_the_text = file_object.read( )
finally:
     file_object.close( )
 

读固定字节
file_object = open('abinfile', 'rb')
try:
    while True:
         chunk = file_object.read(100)
        if not chunk:
            break
         do_something_with(chunk)
finally:
     file_object.close( )
 

读每行
list_of_all_the_lines = file_object.readlines( )

如果文件是文本文件,还可以直接遍历文件对象获取每行:

for line in file_object:
     process line
 

3.写文件
写文本文件
output = open('data', 'w')
 

写二进制文件
output = open('data', 'wb')
 

追加写文件
output = open('data', 'w+')
 

写数据
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
 

写入多行
file_object.writelines(list_of_text_strings)

注意,调用writelines写入多行在性能上会比使用write一次性写入要高。

在处理日志文件的时候,常常会遇到这样的情况:日志文件巨大,不可能一次性把整个文件读入到内存中进行处理,例如需要在一台物理内存为 2GB 的机器上处理一个 2GB 的日志文件,我们可能希望每次只处理其中 200MB 的内容。
在 Python 中,内置的 File 对象直接提供了一个 readlines(sizehint) 函数来完成这样的事情。以下面的代码为例:

file = open('test.log', 'r')sizehint = 209715200   # 200Mposition = 0lines = file.readlines(sizehint)while not file.tell() - position < 0:       position = file.tell()       lines = file.readlines(sizehint)

每次调用 readlines(sizehint) 函数,会返回大约 200MB 的数据,而且所返回的必然都是完整的行数据,大多数情况下,返回的数据的字节数会稍微比 sizehint 指定的值大一点(除最后一次调用 readlines(sizehint) 函数的时候)。通常情况下,Python 会自动将用户指定的 sizehint 的值调整成内部缓存大小的整数倍。

file在python是一个特殊的类型,它用于在python程序中对外部的文件进行操作。在python中一切都是对象,file也不例外,file有file的方法和属性。下面先来看如何创建一个file对象:


file(name[, mode[, buffering]]) 
file()函数用于创建一个file对象,它有一个别名叫open(),可能更形象一些,它们是内置函数。来看看它的参数。它参数都是以字符串的形式传递的。name是文件的名字。
mode是打开的模式,可选的值为r w a U,分别代表读(默认) 写 添加支持各种换行符的模式。用w或a模式打开文件的话,如果文件不存在,那么就自动创建。此外,用w模式打开一个已经存在的文件时,原有文件的内容会被清空,因为一开始文件的操作的标记是在文件的开头的,这时候进行写操作,无疑会把原有的内容给抹掉。由于历史的原因,换行符在不同的系统中有不同模式,比如在 unix中是一个\n,而在windows中是‘\r\n’,用U模式打开文件,就是支持所有的换行模式,也就说‘\r’ '\n' '\r\n'都可表示换行,会有一个tuple用来存贮这个文件中用到过的换行符。不过,虽说换行有多种模式,读到python中统一用\n代替。在模式字符的后面,还可以加上+ b t这两种标识,分别表示可以对文件同时进行读写操作和用二进制模式、文本模式(默认)打开文件。
buffering如果为0表示不进行缓冲;如果为1表示进行“行缓冲“;如果是一个大于1的数表示缓冲区的大小,应该是以字节为单位的。

file对象有自己的属性和方法。先来看看file的属性。


closed #标记文件是否已经关闭,由close()改写 
encoding #文件编码 
mode #打开模式 
name #文件名 
newlines #文件中用到的换行模式,是一个tuple 
softspace #boolean型,一般为0,据说用于print

file的读写方法:


F.read([size]) #size为读取的长度,以byte为单位 
F.readline([size]) 
#读一行,如果定义了size,有可能返回的只是一行的一部分 
F.readlines([size]) 
#把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。 
F.write(str) 
#把str写到文件中,write()并不会在str后加上一个换行符 
F.writelines(seq) 
#把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西。 
file的其他方法:


F.close() 
#关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。如果一个文件在关闭后还对其进行操作会产生ValueError 
F.flush() 
#把缓冲区的内容写入硬盘 
F.fileno() 
#返回一个长整型的”文件标签“ 
F.isatty() 
#文件是否是一个终端设备文件(unix系统中的) 
F.tell() 
#返回文件操作标记的当前位置,以文件的开头为原点 
F.next() 
#返回下一行,并将文件操作标记位移到下一行。把一个file用于for ... in file这样的语句时,就是调用next()函数来实现遍历的。 
F.seek(offset[,whence]) 
#将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。 
F.truncate([size]) 
#把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。
2019-03-26

列出文件

os.listdir('/tmp')

python 生成0-10的随机数

random.randint(0,10)
2019-03-13

开始字符匹配

n.startswith('vm')
2019-03-08

异常处理

            except Exception as e:
                # print(e)
                message = {}
                e_type, e_value, e_traceback = sys.exc_info()
                message['File'] = e_traceback.tb_frame.f_code.co_filename
                message['FunName'] = e_traceback.tb_frame.f_code.co_name
                message['Line']= e_traceback.tb_lineno
                message['content']= str(e_value)
                out = {"code": "400", "message": message, "status": "error"}
                out = json.dumps(out, ensure_ascii=False, indent=4)
                print(out)
                return out

2019-03-07

python requests
https://www.cnblogs.com/ranxf/p/7808537.html
获取网页数据

#coding=utf-8
'''
    股票历史数据抓取
'''
import time
import logging
import requests
import json

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='run.log', level=logging.DEBUG, format=LOG_FORMAT)
# logging.debug("This is a debug log.")
# logging.info("This is a info log.")
# logging.warning("This is a warning log.")
# logging.error("This is a error log.")
# logging.critical("This is a critical log.")

url = 'http://quote.eastmoney.com/stocklist.html'
r = requests.get(url)
print(r.status_code)
print(r.encoding)
r.encoding = 'GBK'
# r.encoding = 'utf-8'
print(r.encoding)
# print(r.json())# 需要先import json   
# print(r.request.headers)
#r1 = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'})      # 带参数的get请求
html = r.text
with open('stocklist.html','w+',encoding='utf-8') as fw:
    # fw.write(html.encode("utf-8"))
    fw.write(html)
2019-03-05

unicdoe 转化为str 字符

105             for j in table.row_values(i):
106                 if isinstance(j, unicode):
107                     b = j.encode('utf-8')
108                 else:
109                     b = str(j)
110                 one.append(str(b))
2019-02-28

flask 发送post数据
request.form
request.data

2019-02-26

python 开启简单http服务80 21

python -m SimpleHTTPServer 80
pip install pyftpdlib
python -m pyftpdlib -p 21
ftp://localhost:21

https://www.cnblogs.com/yili16438/p/d3209323913c6d53e6060fcd8d27e4c0.html

2019-02-1

python 配置django 日志

http://blog.51cto.com/davidbj/1433741

2019-01-17

python open 读取文件报错

codec can't decode byte 0xb9 in position 492: invalid start byte

解决办法

open(file,'rb')    #增加b参数
2019-01-17
生成uuid
import uuid
Project_id = 'P-'+str(uuid.uuid1())
2019-01-16
判断数据类型
print(type(defects).__name__)
        # print(isinstance(defects,list))

日志模块logging

import logging
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT)

logging.debug("This is a debug log.")
logging.info("This is a info log.")
logging.warning("This is a warning log.")
logging.error("This is a error log.")
logging.critical("This is a critical log.")

Django 报错

发送post 请求

Django CSRF Cookie Not Set

解决方法 view中未加装饰器csrf_exempt

@csrf_exempt
def DownloadFinalState(request):
    try:

CSRF防御机制 Django默认对所有的POST请求都进行csrftoken验证,若验证失败则403

判断目录

os.path.isdir()
创建多级目录
os.makedirs(filePath)
判断文件是否存在
os.path.exists(‘1.txt’)

python2.7 下载文件

os.chdir(“目标目录”) #修改当前工作目录
os.getcwd() #获取当前工作目录

import os,urllib2,urllib

url = json.loads(response)[‘Data’][‘DownloadUrl’]
print(url)
python2.7
urllib.urlretrieve(url , ‘./test.xls’)
python3

urllib.request.urlretrieve(url , './test.xls')

python 打开url 包含中文
import urllib.request
import string
from urllib.parse import quote
url = ‘http://xxx/type=%s’%(中文)
print(url)
s = quote(url,safe=string.printable)
f = urllib.request.urlopen(s).read()

修改临时 使用 pip 源
sudo ./pip-2.7 install aliyun-python-sdk-core -i http://mirrors.aliyun.com/pypi/simple/

修改默认pip源
vi ~/.pip/pip.conf

Collecting scipy
  The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS it is recommended to use HTTPS instead, otherwise you may silence this warning and allow it anyways with '--trusted-host mirrors.aliyun.com'.
  Could not find a version that satisfies the requirement scipy (from versions: )
No matching distribution found for scipy
pi@raspberrypi:~/dabai$ sudo pip install scipy -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

[global]
index-url = http://mirrors.aliyun.com/pypi/simple/

1542556800000

时间

unix时间转换
formatTime = datetime.datetime.fromtimestamp(tmp_time/1000)

字符转化为时间

datetime.datetime.strptime('2019-01-08 14:45:36','%Y-%m-%d %H:%M:%S')

计算相差几天

import datetime
t = datetime.datetime.strptime('2019-01-08 14:45:36','%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
(now-t).days

时间------------

time.time()

秒转化为时间
time.strftime(“%Y-%m-%d %H:%M:%S”,time.localtime(1541411593))
time.strftime(“%Y-%m-%d %H:%M:%S”,time.localtime(1542556800))

当前时间
time.strftime(“%Y-%m-%d %H:%M:%S”, time.localtime())

取几天前 几小时 几分钟 几周前时间
print ((datetime.datetime.now()-datetime.timedelta(minutes=2)).strftime(“%Y-%m-%d %H:%M”))
days、seconds、minutes、hours、weeks等

获取周一时间
today = datetime.date.today()
print(today - datetime.timedelta(today.weekday()))

today = datetime.date.today()        # 获取当前日期, 因为要求时分秒为0, 所以不要求时间
weekday = today.weekday()        # 获取当前周的排序, 周一为0, 周日为6
monday_delta = datetime.timedelta(weekday)    # 当前日期距离周一的时间差
sunday_delta = datetime.timedelta(7 - weekday)    # 当前日期距离下周一的时间差
monday = today - monday_delta    # 获取这周一日期
next_monday = today + sunday_delta    # 获取下周一日期

取小数位后2位
round(99.2313242,2)

读excel
sudo pip install xlutils

import datetime,calendar
/*星期日:Calendar.SUNDAY=1
*星期一:Calendar.MONDAY=2
*星期二:Calendar.TUESDAY=3
*星期三:Calendar.WEDNESDAY=4
*星期四:Calendar.THURSDAY=5
*星期五:Calendar.FRIDAY=6
*星期六:Calendar.SATURDAY=7 */

获取上周日

(datetime.datetime.today() - datetime.timedelta(days=time.localtime().tm_wday + 1)).strftime(“%Y-%m-%d”)

获取上周一

(datetime.datetime.today() - datetime.timedelta(days=time.localtime().tm_wday + 7)).strftime(“%Y-%m-%d”)

time.localtime().
int tm_sec; /* 秒 – 取值区间为[0,59] /
int tm_min; /
分 - 取值区间为[0,59] /
int tm_hour; /
时 - 取值区间为[0,23] /
int tm_mday; /
一个月中的日期 - 取值区间为[1,31] /
int tm_mon; /
月份(从一月开始,0代表一月) - 取值区间为[0,11] /
int tm_year; /
年份,其值等于实际年份减去1900 /
int tm_wday; /
星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 /
int tm_yday; /
从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 /
int tm_isdst; /
夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的时候,tm_isdst为0;不了解情况时,tm_isdst()为负。

import datetime
from datetime import timedelta
now = datetime.datetime.now()
#今天
today = now
#昨天
yesterday = now - timedelta(days=1)
#明天
tomorrow = now + timedelta(days=1)

#当前季度
now_quarter = now.month / 3 if now.month % 3 == 0 else now.month / 3 + 1
#本周第一天和最后一天
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6-now.weekday())
#上周第一天和最后一天
last_week_start = now - timedelta(days=now.weekday()+7)
last_week_end = now - timedelta(days=now.weekday()+1)
#本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1)
#上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
#本季第一天和最后一天
month = (now.month - 1) - (now.month - 1) % 3 + 1
this_quarter_start = datetime.datetime(now.year, month, 1)
this_quarter_end = datetime.datetime(now.year, month + 3, 1) - timedelta(days=1)
#上季第一天和最后一天
last_quarter_end = this_quarter_start - timedelta(days=1)
last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)
#本年第一天和最后一天
this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)

#去年第一天和最后一天
last_year_end = this_year_start - timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值