1. 生成6位數字隨機驗證碼
import random
import string
def num_code(length=6):
"""
生成長度為length的數字隨機驗證碼
:param length: 驗證碼長度
:return: 驗證碼
"""
return ''.join(random.choice(string.digits) for i in range(0, length))
2.md5加密
import hashlib
# md5加密
def md5_encrypt(en_str):
"""
使用md5二次加密生成32位的字串
:param en_str: 需要加密的字串
:return: 加密后的字串
"""
md5 = hashlib.md5() # 使用MD5加密模式
md5.update(en_str.encode('utf-8')) # 將引數字串傳入
md5.update(md5.hexdigest().encode('utf-8')) # md5二次加密
return md5.hexdigest()
3. 生成唯一token
import uuid
import hashlib
def only_token():
"""
使用md5加密uuid生成唯一的32位token
:return: 加密后的字串
"""
md5 = hashlib.md5() # 使用MD5加密模式
md5.update(str(uuid.uuid1()).encode('utf-8'))
return md5.hexdigest()
4、發送手機驗證碼
#驗證碼管理表
class AuthCode(models.Model):
name = models.CharField(max_length=10,default=None, null=True, blank=True,verbose_name='姓名')
phone = models.CharField(max_length=11, unique=True, verbose_name='手機號')
code = models.CharField(max_length=6,verbose_name='驗證碼')
purpose = models.IntegerField(default=0,verbose_name='用途:0->注冊驗證 1->找回密碼 2->其它')
sendNum = models.IntegerField(default=0,verbose_name='發送次數')
isCanGet = models.BooleanField(default=0,verbose_name='0->可以獲取,1->不可以獲取')
recentlySendTime = models.DateTimeField(auto_now_add=True,verbose_name='最近一次發送時間')
creation_time = models.DateTimeField(auto_now=True, verbose_name='創建時間')
class Meta:
verbose_name = '手機驗證碼'
verbose_name_plural = verbose_name
實作邏輯
import http.client
import urllib
# 使用互億無線
host = "106.ihuyi.com"
sms_send_uri = "/webservice/sms.php?method=Submit"
# 查看用戶名 登錄用戶中心->驗證碼通知短信>產品總覽->API介面資訊->APIID
account = "你的用戶名"
# 查看密碼 登錄用戶中心->驗證碼通知短信>產品總覽->API介面資訊->APIKEY
password = "你的密碼"
def send_sms(text, mobile):
text = f"您的驗證碼是:{text},請不要把驗證碼泄露給其他人,"
params = urllib.parse.urlencode(
{'account': account, 'password': password, 'content': text, 'mobile': mobile, 'format': 'json'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = http.client.HTTPConnection(host, port=80, timeout=30)
conn.request("POST", sms_send_uri, params, headers)
response = conn.getresponse()
response_str = response.read()
conn.close()
return response_str
if __name__ == '__main__':
mobile = "手機號"
text = '123122'
print(json.loads(send_sms(text, mobile).decode('utf-8')))
5、生成二維碼
import qrcode
import io
def maker_qrcode(url):
"""
生成二維碼
:param url: 需要生成二維碼的url
:return: 回傳圖片位元組流
"""
image = qrcode.make(url) # 創建二維碼片
buffer = io.BytesIO()
# 將圖片內容丟入容器
image.save(buffer, 'png')
# 回傳容器內的位元組
return buffer.getvalue()
或者
from .settings import BASE_DIR
def create_qrcode(name, url):
"""
生成機器掃碼支付二維碼
:param name: 圖片名稱
:param url: 支付路由
:return:
"""
img = qrcode.make(url, border=0) # 創建二維碼片
save_path = BASE_DIR + '/' + name + '.png'
print(save_path)
img.save(save_path)
return img
6.微信群發
# coding=utf8
import itchat, time
itchat.auto_login(True)
SINCERE_WISH = u'祝%s新年快樂!'
friendList = itchat.get_friends(update=True)[35:]
count = 0
for index,friend in enumerate(friendList):
print(index,friend['DisplayName'],friend['NickName'])
itchat.send(SINCERE_WISH % (friend['DisplayName']
or friend['NickName']), friend['UserName'])
time.sleep(2)
print('備注名稱',friend['DisplayName'],'昵稱',friend['NickName'],'用戶名',friend['UserName'])
print("----end----")
"""
# 發送文本
itchat.send('Hello, WeChat!')
# 發送圖片
itchat.send_image('my_picture.png')
# 發送視頻
itchat.send_video('my_video.mov')
# 發送檔案
itchat.send_file('my_file.zip')
"""
7、微信自動回復
# -*- coding=utf-8 -*-
import requests
import itchat
import random
#圖靈機器人
#http://www.tuling123.com/member/robot/1380138/center/frame.jhtml?page=0&child=0獲取apikey
KEY = '你的KEY'
def get_response(msg):
apiUrl = 'http://www.tuling123.com/openapi/api'
data = https://www.cnblogs.com/superwinner/archive/2023/01/15/{'key' : KEY,
'info' : msg,
'userid' : 'wechat-robot',
}
try:
r = requests.post(apiUrl, data=https://www.cnblogs.com/superwinner/archive/2023/01/15/data).json()
return r.get('text')
except:
return
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
defaultReply = 'I received: ' + msg['Text']
robots=['','','']
reply = get_response(msg['Text'])+random.choice(robots)
return reply or defaultReply
itchat.auto_login(enableCmdQR=False)
itchat.run()
8、提取Django中model中的欄位名變成字典、串列
import re
t = """
goods_id = models.IntegerField(verbose_name='商品編號')
label_code = models.CharField(max_length=20, verbose_name='商品標簽')
"""
# 字典
print({k:None for k in re.findall('([a-z_A-Z]+)\s=\s',t)})
# 串列
# print([k for k in re.findall('([a-z_A-Z]+)\s=\s',t)])
輸出
{'goods_id': None, 'lable_code': None}
9、資料庫中給表創建資料
import pymysql
def createData(dataDict,tableName):
"""
給資料表創建資料
:param dataDict: 字典
:param tableName: 表名
:return:
"""
#連接資料庫
conn = pymysql.connect(
host='192.168.0.188', #資料庫所在地址URL
user='root', #用戶名
password='123456', #密碼
database='名稱', #資料庫名稱
port=3306, #埠號
charset='utf8'
)
#拿到查詢游標
cursor = conn.cursor()
clos,value = https://www.cnblogs.com/superwinner/archive/2023/01/15/zip(*dataDict.items())
sql ="INSERT INTO `%s`(%s) VALUES (%s)" % (tableName,
','.join(clos),
','.join(['%s'] * len(value))
)
print(sql)
cursor.execute(sql, value)
conn.commit()
cursor.close()
conn.close()
print('Done')
10.捕捉例外
try:
pass
except 例外型別 as e:
pass
finally:
pass
例外型別
Exception 全部例外
AttributeError 試圖訪問一個物件沒有的屬性,比如foo.x,但是foo沒有屬性x
IOError 輸入/輸出例外;基本上是無法打開檔案
ImportError 無法引入模塊或包;基本上是路徑問題或名稱錯誤
IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊
IndexError 下標索引超出序列邊界,比如當x只有三個元素,卻試圖訪問x[5]
KeyError 試圖訪問字典里不存在的鍵
KeyboardInterrupt Ctrl+C被按下
NameError 使用一個還未被賦予物件的變數
SyntaxError Python代碼非法,代碼不能編譯(個人認為這是語法錯誤,寫錯了)
TypeError 傳入物件型別與要求的不符合
UnboundLocalError 試圖訪問一個還未被設定的區域變數,基本上是由于另有一個同名的全域變數,導致你以為正在訪問它
ValueError 傳入一個呼叫者不期望的值,即使值的型別是正確的
11、獲取當前時間
import datetime
current_time = str(datetime.datetime.now())[:19]
print(current_time)
輸出格式如:2018-10-20 10:01:43
local_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
print(local_time)
12、訂單編號
from random import Random
import time
def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
random = Random()
for i in range(randomlength):
str+=chars[random.randint(0, length)]
return str
def order_num():
"""
生成付款訂單號
:return:
"""
local_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
result = local_time + random_str(5)
return result
print(order_num())
13、mysql自動填寫當前時間
CURRENT_TIMESTAMP

為表添加索引
ALTER table tableName ADD INDEX indexName(columnName)
14、drf動態過濾查詢
# page.py
from rest_framework.pagination import PageNumberPagination
class UserPagination(PageNumberPagination):
"""用戶分頁器"""
page_size = 10 # 默認的頁面資料數量
page_query_param = 'page' # 定制取資料頁碼key
page_size_query_param = 'page_size' # 默認取資料頁碼key
max_page_size = 15 # 資料每頁取值的最大上限
# serializers.py
from rest_framework import serializers
from user.models import UserInfo
class UserSerializers(serializers.ModelSerializer):
"""用戶識訓地址"""
class Meta:
model = UserInfo
# 所有欄位
#fields = '__all__'
fields = ['name', 'code', 'title', 'province', 'city',
'quxian', 'address', 'code__gte', 'code__lte']
# 顯示外鍵
depth = 2
# views.py
class MachineViews(APIView):
def get(self, request, *args, **kwargs):
# 從前端獲取出來的過濾引數,決議成字典傳進filter()函式中
# 動態過濾,
kwargs = {}
# 表中的欄位名
columns = ['name', 'code', 'title', 'province', 'city',
'quxian', 'address', 'code__gte', 'code__lte']
for k, v in request.query_params.items():
if k not in columns:
return Response('引數不對', status=status.HTTP_400_BAD_REQUEST)
if v:
kwargs[k] = v
users = UserInfo.objects.filter(**kwargs)
page = UserPagination()
page_goods_list = page.paginate_queryset(users, self.request, self)
ser = UserSerializers(page_goods_list, many=True)
return page.get_paginated_response(ser.data)
15、linux后臺運行python程式
nohup /home/project_venv/user/bin/python3 -u /home/user/user_server.py >> /home/user/user.log 2>&1 &
16、追加外鍵
ALTER TABLE tb_commentPhoto ADD CONSTRAINT FK_comment_phone
FOREIGN KEY tb_goodsComment(id) REFERENCES tb_commentPhoto(comment_id);
17、寫/讀CSV檔案,查看是否存在,若存在就從csv中洗掉
import csv
import random
import string
def create_invite_code(random_code_pool=None, length=6, num=10, is_append=False):
"""
創建隨機邀請碼,并寫入txt檔案
:param: random_code_pool 隨機邀請碼
:param: length 邀請碼長度
:param: num 邀請碼個數
:param: is_append True追加,False 覆寫
:return:
"""
if not random_code_pool:
code_pool = string.ascii_uppercase + string.digits
random_code_pool = []
for i in range(num):
s = ''
for _ in range(length):
s += random.choice(code_pool)
if s and s not in random_code_pool:
random_code_pool.append(s)
# 寫入方法,是追加還是覆寫
write_method = 'a+' if is_append else 'w'
# 寫入檔案
with open('./invite_code.csv', write_method, newline='') as f:
writer = csv.writer(f)
for rowData in random_code_pool:
# 按行寫入
writer.writerow((rowData,))
def check_invite_code(code):
"""
查看邀請碼是否存在txt檔案中,
若存在就回傳True,并在txt檔案中洗掉
若不存在就回傳False
:param code:
:return:
"""
code_pool = []
with open('./invite_code.csv', 'r', encoding='utf-8',errors='ignore') as f:
allFileInfo = csv.reader(f)
for row in allFileInfo:
code_pool.append(row[0])
if code in code_pool:
# 洗掉查詢的code
code_pool.pop(code_pool.index(code))
# 重新寫入檔案
create_invite_code(code_pool,is_append=False)
return True
return False
if __name__ == '__main__':
# create_invite_code(length=9,num=100)
print(check_invite_code('WJ4PSTJG2'))
18、django中從request獲取訪問路徑
print('獲取相對路徑', request.get_full_path())
print('獲取絕對路徑', request.build_absolute_uri())
print(request.build_absolute_uri('?'))
print(request.build_absolute_uri('/')[:-1].strip("/"))
print(request.build_absolute_uri('/').strip("/"))
print(request.build_absolute_uri('/'))
print('----------')
print(request.META['HTTP_HOST'])
print(request.META['PATH_INFO'])
print(request.META['QUERY_STRING'])
iphost = request.META.get('REMOTE_ADDR', '') # 獲取訪問來源IP
# 輸出如:
獲取相對路徑 /QRcode/?d=1
獲取絕對路徑 http://127.0.0.1:8000/QRcode/?d=1
http://127.0.0.1:8000/QRcode/
http://127.0.0.1:8000
http://127.0.0.1:8000
http://127.0.0.1:8000/
----------
127.0.0.1:8000
/QRcode/
d=1
19、Django收集靜態檔案
先在專案根目錄下創建一個static檔案夾
然后在settings.py中設定
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
最后執行下面的命令:
python manage.py collectstatic
20、xadmin插件
https://www.cnblogs.com/lanqie/p/8340215.html
21、uwsgi自動重啟
[uwsgi]
# 使用nginx連接時 使用
socket=0.0.0.0:2019
# 直接作為web服務器使用
#http=0.0.0.1:8000
# 配置工程目錄
chdir=/home/user
# 配置專案的wsgi目錄,相對于工程目錄
wsgi-file=user/wsgi.py
virtualenv=/home/project_venv/user
#配置行程,執行緒資訊
processes=1
threads=1
enable-threads=True
master=True
pidfile=uwsgi.pid
daemonize=uwsgi.log
#啟動uwsgi的用戶名和用戶組
uid=root
gid=root
#uwsgi自動重啟
py-autoreload=1
22、谷歌瀏覽器快捷鍵
瀏覽器快取
Ctrl+Shift+Del 清除Google瀏覽器快取的快捷鍵
Ctrl+Shift+R 重新加載當前網頁而不使用快取內容
23、git克隆分支
git clone -b dev 地址
24、mysql更新陳述句、新增列、洗掉列
update user set name='張三' where id=111
# 洗掉
DELETE FROM table_name [WHERE Clause]
# 增加欄位
alter table 表名 add column 列名 型別;
# 洗掉欄位
alter table 表名 dropcolumn 列名 ;
25、洗掉指定格式的檔案
import os
import re
def remove_specified_format_file(file_dir, format_name):
"""
洗掉指定格式的檔案
:param file_dir: 檔案根目錄
:param format_name: 格式
:return:
"""
for root, dirs, files in os.walk(file_dir):
# print(root) #當前目錄路徑
# print(dirs) #當前路徑下所有子目錄
# print(files) #當前路徑下所有非目錄子檔案
for file in files:
if re.match(format_name, file):
print(os.path.join(root, file))
os.remove(os.path.join(root, file))
remove_specified_format_file(r'D:\學習\LDC\java', r'\._*')
26、計算檔案總數
import os
def file_count(file_dir):
"""
:param file_dir: 檔案根目錄
:return:
"""
count = 0
for root, dirs, files in os.walk(file_dir):
# print(root) #當前目錄路徑
# print(dirs) #當前路徑下所有子目錄
# print(files) #當前路徑下所有非目錄子檔案
count += len(files)
return count
print(file_count(r'D:\學習\LDC\java\Java學習\newEstore\estore\js'))
27、計算檔案夾大小
import os
def file_size(file_dir):
"""
洗掉指定格式的檔案
:param file_dir: 檔案根目錄
:return:
"""
size = 0
for root, dirs, files in os.walk(file_dir):
# print(root) #當前目錄路徑
# print(dirs) #當前路徑下所有子目錄
# print(files) #當前路徑下所有非目錄子檔案
for file in files:
size += os.path.getsize(os.path.join(root, file))
# M為單位
return size / 1024 / 1024
file_name = r'D:\學習'
print(file_size(file_name))
28、Django實作jsonp跨域
# html
$.ajax({
url: '請求路由',
type: 'GET',
dataType: 'JSONP',
data:{
code: 'yes',
},
jsonp: 'callback',
success: function(res) {
var selectData = https://www.cnblogs.com/superwinner/archive/2023/01/15/$.parseJSON(res);
alert(selectData);
},
error: function(err) {
}
})
# views.py
def get(self, request, *args, **kwargs):
code = request.GET.get('code', '')
# 跨域請求
callback = request.GET.get('callback', '')
return HttpResponse("%s('%s')" % (callback, json.dumps({'code': code})), status=status.HTTP_200_OK)
cors解決跨域
https://www.cnblogs.com/wxiaoyu/p/9578848.html
29、微信獲取用戶資訊
參考:https://blog.csdn.net/weixin_39735923/article/details/79202563
30、uwsgi初始配置問題
https://blog.csdn.net/weixin_39735923/article/details/79202563
31、django中drf序列化
# 序列化器
class MsgSerializers(serializers.ModelSerializer):
addtime = serializers.DateTimeField(read_only=True, format="%Y-%m-%d %H:%M:%S")
hasread = serializers.CharField(source='get_hasread_display')
msgtype = serializers.CharField(source='get_msgtype_display')
class Meta:
model = MallMsg
# 可以混合使用
fields = '__all__' # '__all__' 所有欄位
# 資料庫層級控制(序列化鏈表操作)
# depth = 1 # 外鍵層級
#分頁器
from rest_framework.pagination import PageNumberPagination
class MyLimitOffsetPagination(PageNumberPagination):
page_size = 3 # 默認的頁面資料數量
page_query_param = 'page' # 定制取資料頁碼key ?
page_size_query_param = 'page_size' # 默認取資料頁碼key &
max_page_size = 15 # 資料每頁取值的最大上限
32、第三方庫
安裝openssl
pip3 install pyOpenSSL
33、requests請求https攜帶CA證書
import OpenSSL
import requests
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
def p12_to_pem(certname, pwd):
"""
從.p12檔案中提取pem
:param certname:
:param pwd:
:return:
"""
pem_name = certname + ".pem"
f_pem = open(pem_name, 'wb')
p12file = certname + ".p12"
p12 = OpenSSL.crypto.load_pkcs12(open(p12file, 'rb').read(), pwd)
f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()))
f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate()))
ca = p12.get_ca_certificates()
if ca is not None:
for cert in ca:
f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
f_pem.close()
return pem_name
def post_cert_request(url, data,header, certname, pwd):
"""
使用證書發起https請求
:param url:
:param data:
:param certname:
:param pwd:
:return:
"""
if (certname != ""):
cert = p12_to_pem(certname, pwd)
else:
cert = None
r = requests.post(url, header=header, data=https://www.cnblogs.com/superwinner/archive/2023/01/15/data, cert=cert)
return r
34、django創建快取命令
python manage.py createcachetable 快取表名
35、Django 更改超級用戶密碼
在工程檔案目錄下敲入:
python manage.py shell
再在python互動界面輸入:
from django.contrib.auth.models import User
user = User.objects.get(username = '用戶名')
user.set_password('密碼')
user.save()
36、restframe使用快取
https://blog.csdn.net/Odyssues_lee/article/details/80872586
37、資料庫
select * from user where ISNULL(code)
update user set code='111',info='微信' where ISNULL(code)
38、linux常用命令[[Linux]]
tail -f 日志名 實時監控日志
tail -f 80_v10.log
netstat -na|grep 80 查看埠tcp連接數
netstat -na|grep 80 | wc -l 計算埠tcp連接數
ps -ef|grep python 查看有多少python程式在運行
gunzip 2015.csv.gz # 解壓
unzip 19.zip # 解壓zip
wc -l 2015.csv # 查看行數
apt install lrzsz # 安裝
sz 檔案名 # 下載檔案
查找檔案
find / -name 檔案名
匹配執行過的以find為開頭的命令
history | grep find
39、xadmin禁止增加、洗掉
# models.py
# 用戶管理
class UserManage(models.Model):
name = models.CharField(max_length=20, verbose_name='用戶名')
phone = models.CharField(max_length=11, unique=True, verbose_name='手機號')
code = models.CharField(max_length=11, unique=True, verbose_name='編號')
user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, verbose_name='管理員')
# adminx.py
# 用戶串列
class UserAdmin(object):
list_display = [ 'code', 'phone', 'name',]
search_fields = ['code', 'phone']
list_filter = ['code', 'phone']
list_editable = ['name'] # 資料即時編輯
readonly_fields = ['code', 'phone', 'name'] # 只讀欄位,不能編輯
model_icon = 'fa fa-square'
model = UserInfo
def has_delete_permission(self, *args, **kwargs):
# 禁止洗掉
if args:
return True
return False
def has_add_permission(self,*args,**kwargs):
# 禁止增加
return False
def save_models(self):
# 用戶級別設定
self.new_obj.user = self.request.user
flag = self.org_obj is None and 'create' or 'change'
if flag == 'create':
# 對密碼欄位進行加密
self.new_obj.password = encrypt_oracle(self.new_obj.password)
elif flag == 'change':
if 'password' in self.change_message():
self.new_obj.password = encrypt_oracle(self.new_obj.password)
else:
pass
super().save_models()
xadmin.site.register(UserInfo, UserAdmin)
40、時間格式字串相減
import datetime
import time
start = str(datetime.datetime.now())[:19]
time.sleep(60)
end = str(datetime.datetime.now())[:19]
print(start,end)
link_start = datetime.datetime.strptime(start, '%Y-%m-%d %H:%M:%S')
link_end = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')
link_min = round((link_end - link_start).seconds / 60, 2)
print(link_min,'分鐘')
41、顯示回圈進度條
參考:https://blog.csdn.net/zejianli/article/details/77915751
from tqdm import tqdm,trange
from time import sleep
text = ""
for char in tqdm(["a", "b", "c", "d"]):
text = text + char
sleep(1)
# 方式二
import time
def process_bar(percent, index, total,start_time, start_str='', end_str='', total_length=100):
# 進度條
percent_length = int(percent)
bar = '\r' + start_str + ('\033[1;31;41m \033[0m' * percent_length + '\033[1;37;47m \033[0m' * (
total_length - percent_length)) + f' {round(index / total * 100, 2)}% ' + f' {index}|{end_str}'+ f' |已進行時間: {round(time.time() - start_time, 2)}秒'
print(bar, end='', flush=True)
if __name__ == '__main__':
data_set = [i for i in range(23)]
i = 0
start_time = time.time()
total = len(data_set)
end_str = '{}'.format(total)
for data in data_set:
time.sleep(1)
i += 1
process_bar(i * 100 / total, i, total, start_time, start_str='', end_str=end_str, total_length=100)
# 方式三
import sys
import time
d = [i for i in range(100)]
for i in range(len(d)):
time.sleep(1)
sys.stdout.write('\r>> Downloading %.2f%%' % (float(i) / float(len(d)) * 100.0))
sys.stdout.flush()
42、把串列中的字典轉成csv檔案
import pandas as pd
lists = [{'a':1,'b':2},{'a':2,'b':3}]
df = pd.DataFrame(lists)
print(df)
df.to_csv('result2.csv')
43、windows添加右鍵新建MarkDown檔案
在網上下載Typora軟體安裝后
1、在桌面上新建一個txt檔案,輸入以下內容:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.md\ShellNew]
"NullFile"=""
"FileName"="template.md"
2、另存為,改后綴為.reg,保存型別為.txt,編碼為Unicode

3、雙擊運行,確定,重啟電腦,此時在桌面右鍵就有了新建md檔案
44、redis設定值定時過期
import datetime
import redis
redis_client = redis.Redis(
host='127.0.0.1',
port=6379,
db=0,
password='123456'
)
def redis_set():
"""
redis設定值定時過期
:return:
"""
global redis_client
redis_client.set('name','ldc')
now = datetime.datetime.now()
# 設定‘name’50秒過期
expire_time = now + datetime.timedelta(hours=0, minutes=0, seconds=50)
redis_client.expireat('name', expire_time)
if __name__ == '__main__':
redis_set()
45、linux根據埠殺行程
import os
def killport(port):
command = '''kill -9 $(netstat -nlp | grep :''' + str(port) + ''' | awk '{print $7}' | awk -F"/" '{ print $1 }')'''
os.system(command)
# 開始執行
if __name__ == '__main__':
port = 4237
killport(port)
46、監控linux網路流量
iftop -n -N -i eth0
nethogs eth0
vim +/字串 檔案
47、win10添加右鍵打開cmd
通過添加注冊表項實作
win + r 輸入 regedit
找到注冊表位置:HKEY_CLASSES_ROOT\Directory\Background\shell\
右鍵“shel”l,新建“項”,命名為“以管理員身份打開cmd”,
右鍵“以管理員身份打開cmd”,新建“DWORD(32位)值”,命名為"ShowBasedOnVelocityId",值為“639bc8”
右鍵“以管理員身份打開cmd”,新建“項”,命名為“command”
右鍵“command”,點擊“默認”,點擊“修改”,填寫數值為 cmd.exe /s /k pushd “%V”
48、xadmin后臺無法顯示下拉框完整內容
解決方案 在根目錄中找到/static/xadmin/vendor/selectize/selectize.bootstrap3.css
在331行后加入 position: static;

49、xadmin單點登錄
使用中間件實作,
新建一個utils.py檔案,存放以下代碼:
from django.contrib.sessions.models import Session
from django.db.models import Q
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
class XadminMiddleware(MiddlewareMixin):
def process_request(self, request):
"""xadmin后臺單點登錄"""
PATH_INFO = request.META.get('PATH_INFO', '')
if PATH_INFO and 'xadmin' in PATH_INFO:
request.session.clear_expired() # 清除過期的key
session_key = request.session.session_key
for session in Session.objects.filter(~Q(session_key=session_key), expire_date__gte=timezone.now()):
data = https://www.cnblogs.com/superwinner/archive/2023/01/15/session.get_decoded()
if data.get('_auth_user_id', None) == str(request.user.id):
session.delete()
然后在urls.py中設定:
urlpatterns = [
...
re_path('^xadmin/', xadmin.site.urls),
...
]
然后在settings.py中注冊中間件
MIDDLEWARE = [
...
'utils.xadminauth.XadminMiddleware',
...
]
SESSION_COOKIE_AGE = 1209600 # 設定過期時間
SESSION_SAVE_EVERY_REQUEST = Ture # 每次請求都更新
【參考】 https://blog.csdn.net/Python_anning
50、Django restful 多個models資料表序列化合并回傳(一次請求回傳多個序列化器資料)
# 匯入第三方包
pip install django-crispy-forms==1.7.2
# 在settings.py中添加應用
INSTALLED_APPS = [
...
'drf_multiple_model',
'rest_framework',
...
]
# 在views.py中使用
from drf_multiple_model.pagination import MultipleModelLimitOffsetPagination
from drf_multiple_model.views import ObjectMultipleModelAPIView
class LimitPagination(MultipleModelLimitOffsetPagination):
# 多個models資料表聯合查詢,分頁,每頁限制資料10條
default_limit = 10
class StudentSerializers(serializers.ModelSerializer):
"""學生表序列化器"""
# merchant = MerchantSerializers()
register_time = serializers.DateTimeField(read_only=True, format="%Y-%m-%d %H:%M:%S")
class Meta:
model = Student
fields = '__all__'
class ClassesSerializers(serializers.ModelSerializer):
"""班級表序列化器"""
# merchant = MerchantSerializers()
add_time = serializers.DateTimeField(read_only=True, format="%Y-%m-%d %H:%M:%S")
class Meta:
model = Classes
fields = '__all__'
class SchoolSerializers(serializers.ModelSerializer):
"""學校表序列化器"""
# merchant = MerchantSerializers()
add_time = serializers.DateTimeField(read_only=True, format="%Y-%m-%d %H:%M:%S")
class Meta:
model = School
fields = '__all__'
class StudentInfo(ObjectMultipleModelAPIView):
# 獲取學生資訊,班級資訊,學校資訊
def get(self, request, *args, **kwargs):
uid = request.GET.get('uid', '') # 學生id
cid = request.GET.get('cid', '') # 班級id
sid = request.GET.get('sid', '') # 學校id
self.querylist = [
{'queryset': Student.objects.filter(id=uid).order_by('-id'),
'serializer_class': StudentSerializers, 'label': 'student', },
{'queryset': Classes.objects.filter(id=cid).order_by('-id'),
'serializer_class': ClassesSerializers, 'label': 'classes', },
{'queryset': School.objects.filter(id=sid).order_by('-id'),
'serializer_class': SchoolSerializers, 'label': 'school', },
]
return self.list(request, *args, **kwargs)
pagination_class = LimitPagination
51、 Django序列化器回傳外鍵關聯資料
通過 related_name='goods_price’把兩個表關聯起來,當回傳Goods的資訊時也會回傳相應的GoodsPrice資訊
class GoodsPriceSerializers(serializers.ModelSerializer):
"""商品價格表序列化器"""
class Meta:
model = GoodsPrice
fields = ['price']
class GoodsSerializers(serializers.ModelSerializer):
"""商品表序列化器"""
goods_price = GoodsPriceSerializers(many=True, read_only=True)
class Meta:
model = Goods
fields = ['title','goods_price']
depth = 2
class Goods(models.Model):
"""商品表"""
title = models.CharField(max_length=50, verbose_name='商品名稱')
class Meta:
db_table = 'goods'
verbose_name = '商品資訊表'
verbose_name_plural = verbose_name
def __str__(self):
return self.title
class GoodsPrice(models.Model):
"""商品價格表,通過外鍵關聯商品資訊表"""
price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='售價')
goods = models.ForeignKey(to='Goods', related_name='goods_price', on_delete=models.SET_NULL, blank=True, null=True,verbose_name='商品')
def __str__(self):
return str(self.price)
class Meta:
managed = True
db_table = 'goodsPrice'
verbose_name = '商品售價'
verbose_name_plural = verbose_name
52、python Django通過User Agent判斷請求來源是微信掃一掃或者是支付寶掃一掃
class Footest(APIView):
def get(self, request, *args, **kwargs):
# print(request.META)
if 'MicroMessenger' in request.META['HTTP_USER_AGENT']:
return Response(data=https://www.cnblogs.com/superwinner/archive/2023/01/15/{'msg': '訪問來源是微信'})
elif 'AlipayClient' in request.META['HTTP_USER_AGENT']:
return Response(data=https://www.cnblogs.com/superwinner/archive/2023/01/15/{'msg': '訪問來源是支付寶'})
else:
return Response(data=https://www.cnblogs.com/superwinner/archive/2023/01/15/{'msg': '訪問來源是其他'})
User Agent中文名為用戶代理,簡稱 UA,它是一個特殊字串頭,使得服務器能夠識別客戶使用的作業系統及版本、CPU 型別、瀏覽器及版本、瀏覽器渲染引擎、瀏覽器語言、瀏覽器插件等,
瀏覽器的 UA 字串
標準格式為: 瀏覽器標識 (作業系統標識; 加密等級標識; 瀏覽器語言) 渲染引擎標識 版本資訊
獲取user-Agent 之后,
通過識別MicroMessenger或者AlipayClient這樣的關鍵字應該就可以判斷是微信還是支付寶
【參考文章】 https://blog.csdn.net/fly910905/article/details/82498813?utm_source=blogxgwz4
53、xadmin后臺集成’匯入‘插件,匯入excel檔案
效果圖:

1、添加
在虛擬環境根目錄\Lib\site-packages\xadmin\plugins中添加excel.py檔案

from xadmin.views import BaseAdminPlugin, ListAdminView
from django.template import loader
import xadmin
class ListExcelImportPlugin(BaseAdminPlugin):
# 重寫init_request
import_excel = False
def init_request(self, *args, **kwargs):
return self.import_excel
def block_top_toolbar(self, context, nodes):
# 這里 xadmin/excel/model_list.top_toolbar.import.html 是自己寫的html檔案
nodes.append(loader.render_to_string("xadmin/excel/model_list.top_toolbar.import.html"))
xadmin.site.register_plugin(ListExcelImportPlugin, ListAdminView)
在虛擬環境根目錄\Lib\site-packages\xadmin\plugins__init__.py中
PLUGINS = (
...
'excel',
...
)
2、添加html檔案

在虛擬環境根目錄\Lib\site-packages\xadmin\templates\xadmin\中增加檔案夾excel,在檔案夾中添加model_list.top_toolbar.import.html檔案
{% load i18n %}
<div >
<a data-toggle="dropdown" href="https://www.cnblogs.com/superwinner/archive/2023/01/15/#">
<i ></i> 匯入資料 <span ></span>
</a>
<ul role="menu" aria-labelledby="dLabel">
<li><a data-toggle="modal" data-target="#export-modal-import-excel"><i ></i> 匯入
Excel</a></li>
</ul>
<div id="export-modal-import-excel" >
<div >
<div >
<form method="post" action="" enctype="multipart/form-data">
<!--{% csrf_token %}-->
<div >
<button type="button" data-dismiss="modal" aria-hidden="true">×</button>
<h4 >匯入 Excel</h4>
</div>
<div >
<input type="file" onchange="fileChange(this)" name="excel" id="submit_upload">
</div>
<div >
<button type="button" data-dismiss="modal">{% trans "Close" %}</button>
<button type="button" id="submit_upload_b"><i ></i> 匯入
</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dalog -->
</div><!-- /.modal -->
</div>
<script type="text/javascript">
function fileChange(target) {
//檢測上傳檔案的型別
var imgName = document.all.submit_upload.value;
var ext, idx;
if (imgName == '') {
document.all.submit_upload_b.disabled = true;
alert("請選擇需要上傳的 xls 檔案!");
return;
} else {
idx = imgName.lastIndexOf(".");
if (idx != -1) {
ext = imgName.substr(idx + 1).toUpperCase();
ext = ext.toLowerCase();
if (ext != 'xls' && ext != 'xlsx') {
document.all.submit_upload_b.disabled = true;
alert("只能上傳 .xls 型別的檔案!");
return;
}
} else {
document.all.submit_upload_b.disabled = true;
alert("只能上傳 .xls 型別的檔案!");
return;
}
}
}
$(document).ready(function () {
$('#submit_upload_b').click(function () {
var form_data = https://www.cnblogs.com/superwinner/archive/2023/01/15/new FormData();
var file_info = $('#submit_upload')[0].files[0];
form_data.append('file', file_info);
form_data.append('file_source', $('.breadcrumb li').eq(1).text().trim());
var url = window.location.protocol + '//' + window.location.host + '/importkdorderno/'
$.ajax({
url: url,
type: 'POST',
data: form_data,
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", $.getCookie("csrftoken"))
},
processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
success: function (res) {
alert(res.msg);
window.location.reload();
},
error: function (err) {
}
});
});
})
</script>
3、在views.py處理上傳的excel檔案
import pandas as pd
from rest_framework.views import APIView
class ImportKDOrderNo(APIView):
def post(self, request, *args, **kwargs):
file = request.FILES.get('file')
# read = InMemoryUploadedFile().open()
data = https://www.cnblogs.com/superwinner/archive/2023/01/15/pd.read_excel(file) # 使用pandas處理excel檔案
file_source = request.POST.get('file_source', '') # 檔案來源
if '訂單號' and '物流單號' not in data:
return Response(data=https://www.cnblogs.com/superwinner/archive/2023/01/15/{'msg': '檔案格式有誤,第一行第一列應該為【訂單號】,第一行第二列應該為【物流單號】'})
ordernos = data['訂單號']
logistics = data['物流單號']
for i in range(len(ordernos)):
print('訂單號', ordernos[i], '物流單號', logistics[i])
return Response(data=https://www.cnblogs.com/superwinner/archive/2023/01/15/{'msg': '上傳成功'})
4、在urls.py中添加訪問路由
from django.urls import path
from 你的應用名稱 import views
app_name = '你的應用名稱'
urlpatterns = [
# 其他路由
...
# 匯入物流單號
path('importkdorderno/', views.ImportKDOrderNo.as_view(), name='importkdorderno'),
]
54、Django中查找今天進賬金額
views.py
from datetime import datetime
class CountFee(APIView):
def get(self, request, *args, **kwargs):
# 獲取當前時間的年月日,然后使用聚合函式添加fee欄位的值
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
count_fees = FeeDetail.objects.filter(addtime__year=year, addtime__month=month, addtime__day=day).aggregate(Sum('fee'))
all_fee = count_fees['fee__sum'] if count_fees['fee__sum'] else 0
print(all_fee)
return Response({'code': 1, 'msg': 'success', 'data': {'all_fee': all_fee}})
55、判斷是什么系統
import platform
PlATFORM = platform.system()
if PlATFORM == "Linux":
print('linux')
else:
print('其他')
56、sql查詢
# 聯合更新
update malluser set master_master_id=3 where master_id in (select a.id from (select id from malluser where id like '15%')a)
# 統計某欄位重復資料
SELECT phone, COUNT(*) AS sumCount FROM malluser GROUP BY phone HAVING sumCount > 1;
57、 xadmin后臺洗掉資料出現錯誤
get_deleted_objects() takes 3 positional arguments but 5 were given
這是由于Django2.1版本和xadmin不兼容導致的
知道虛擬環境\Lib\site-packages\xadmin\plugins\actions.py
修改93行,
把
deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
queryset, self.opts, self.user, self.admin_site, using)
改為
deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
queryset, self.user, self.admin_site)
然后在adminx.py檔案中對應的模型類中允許洗掉
class MaterialAdmin(object):
"""素材庫分類"""
list_display = ['id', 'name', 'class_id', 'is_delete', 'addtime']
def has_delete_permission(self, *args, **kwargs):
return True
58、xdamin限制用戶點擊
//如果登錄z=xadmin后臺的賬號不是【root】的就不能點擊更新操作
var master_name = $('#top-nav').find('strong').text();
master_name = master_name.substring(4);
if(master_name != 'root'){
$(".grid-item a").each(function(index, element) {
$(this).attr('href','#');
});
}
59、獲取公眾號關注url
在微信網頁版,打開公眾號,點擊右上角“…”,在彈框中選擇右下角中間的“查看歷史記錄”,然后在彈框中選擇左上角倒數第一個,“用默認瀏覽器打開”,就可以在打開的瀏覽器中獲取該公眾號的關注url,當把這個url發給好友時,好友點開的就是去關注公眾號的頁面,
60、xadmin后臺用戶操作表權限
虛擬環境根目錄\Lib\site-packages\xadmin\views\base.py
可以找到:

在專案子應用下的adminx.py中使用
import xadmin
from machine.models import Machine
class MachineAdmin(object):
list_display = ['code',] # 顯示的欄位
search_fields = ['code'] # 搜索的欄位
list_filter = ['code', 'is_delete'] # 過濾的欄位
ordering = ('-id',) # 按id降序排序
list_editable = ['is_delete', ] # 資料即時編輯
list_per_page = 30 # 每頁顯示資料數量
model_icon = 'fa fa-cog fa-spin' # 左側顯示的小圖示
def has_delete_permission(self, *args, **kwargs):
# 洗掉權限
if self.request.user.is_superuser: # 管理員才能增加
return True
return False
def has_add_permission(self, *args, **kwargs):
if self.request.user.is_superuser: # 管理員才能增加
return True
return False
def has_change_permission(self, *args, **kwargs):
if self.request.user.is_superuser: # 管理員才能修改
return True
return False
def queryset(self):
qs = super(MachineAdmin, self).queryset()
if self.request.user.is_superuser: # 管理員可以查看所有
return qs
else:
# 登錄用戶只能看到自己修改的資料
return qs.filter(master_id=self.request.user.last_name)
xadmin.site.register(MallMachine, MallMachineAdmin)
61、使用nginx部署專案
先在/etc/nginx/sites-available中創建一個組態檔,檔案名為test(注意沒有后綴):
#設定虛擬主機配置
server {
#偵聽80埠
listen 80;
listen 443 ssl;
#定義使用 www.nginx.cn訪問
#ssl on;
server_name xxx.xxx.com;
#定義服務器的默認網站根目錄位置
root /root/專案名稱;
ssl_session_timeout 5m;
ssl_certificate /etc/nginx/cert/xxx.pem;
ssl_certificate_key /etc/nginx/cert/xxx.key;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
#設定本虛擬主機的訪問日志
#access_log logs/nginx.access.log main;
#默認請求
location / {
#倒入了uwsgi的配置
include uwsgi_params;
client_max_body_size 50m;
#連接uwsgi的超時時間
# uwsgi_connect_timeout 30;
#設定了uwsig服務器位置
uwsgi_pass 127.0.0.1:8002;
}
location /static{
alias /root/專案名稱/static;
}
location /media {
alias /root/專案名稱/media;
}
}
其中xxx.xxx.com表示域名.如果沒有https,就使用#把ssl注釋掉就可以了,
然后把test映射到/etc/nginx/sites-enabled
命令
ln -s /etc/nginx/sites-available/test /etc/nginx/sites-enabled/test
即可
注意:
uwsgi中配置listen=1024時,啟動uwsgi時可能會報錯:
django + uwsgi + nginx 日志Listen queue size is greater than the system max net.core.somaxconn (128).
解決方法:
修改系統引數
/proc/sys/net/ipv4/tcp_max_syn_backlog 原來2048 改為8192
/proc/sys/net/core/somaxconn 原來128 改為262144
重啟nginx
nginx -s reload
62、xadmin后臺發送郵件找回密碼

輸入你用戶系結的郵箱

想要發送郵件,需要在settings.py中設定郵件發送器
settings.py最下面增加
# ------------------------郵箱配置-----------------------------------------
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #把要發送的郵件顯示再控制臺上,方便除錯
EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.qq.com' # 如果是 163 改成 smtp.163.com
EMAIL_PORT = 465
EMAIL_HOST_USER = '郵箱賬號' # 帳號
EMAIL_HOST_PASSWORD = '授權碼' # 到郵箱里開通
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
由于django2與xadmin有些地方不兼容,需要修改原始碼:
找到虛擬環境根目錄\Lib\site-packages\xadmin\plugins\passwords.py
在passwords.py檔案中大概79行,修改為
return password_reset_confirm(request=request, uidb36=uidb36, token=token,
template_name=self.password_reset_confirm_template,
token_generator=self.password_reset_token_generator,
set_password_form=self.password_reset_set_form,
post_reset_redirect=self.get_admin_url('xadmin_password_reset_complete'),
current_app=self.admin_site.name, extra_context=context).dispatch(request=request,
uidb64=uidb36,token=token)
找到虛擬環境根目錄Lib\site-packages\django\contrib\auth\views.py
在views.py檔案中大概258行,增加:
# 成功后跳轉路由,根據自己實際來定
self.success_url = self.request.build_absolute_uri('/') + 'xadmin/'

63、xadmin外鍵下拉框添加過濾
class MallGoodsAdmin(object):
"""商品管理"""
list_display = ['id', 'show_photo', 'nickname', 'merchant', 'goods_class', 'label',]
search_fields = ['nickname']
list_filter = ['goods_class', 'label',]
model_icon = 'fa fa-bars'
list_editable = ['goods_class', ]
#,重寫虛擬環境根目錄下\Lib\site-packages\xadmin\views\edit.py中的formfield_for_dbfield
def formfield_for_dbfield(self, db_field, **kwargs):
# 對MallGoodsClass這個表項的下拉框選擇進行過濾
# MallGoods中有一個goods_class商品分類外鍵MallGoodsClass,過濾掉外鍵MallGoodsClass中
# master_class為空的值
if db_field.name == "goods_class":
kwargs["queryset"] = MallGoodsClass.objects.filter(master_class__isnull=False)
# 對assigned_recipient這個表項的下拉選擇進行過濾
return db_field.formfield(**dict(**kwargs))
return super().formfield_for_dbfield(db_field, **kwargs)
xadmin.site.register(models.MallGoods, MallGoodsAdmin)
64、xadmin即時編輯器去掉空標簽

虛擬環境根目錄下\Lib\site-packages\xadmin\plugins\editable.py,在大概
129行增加:
form.fields[fields[0]].empty_label = None

65、用戶增加的小組件,讓其他用戶可見
找到虛擬環境根目錄\Lib\site-packages\xadmin\views\dashboard.py
在548行、554行

改為:
@filter_hook
def get_widgets(self):
if self.widget_customiz:
portal_pos = UserSettings.objects.filter(
key=self.get_portal_key())
if len(portal_pos):
portal_pos = portal_pos[0].value
widgets = []
if portal_pos:
user_widgets = dict([(uw.id, uw) for uw in UserWidget.objects.filter(page_id=self.get_page_id())])
for col in portal_pos.split('|'):
ws = []
for wid in col.split(','):
try:
widget = user_widgets.get(int(wid))
if widget:
ws.append(self.get_widget(widget))
except Exception as e:
import logging
logging.error(e, exc_info=True)
widgets.append(ws)
return widgets
return self.get_init_widget()
66、pip install uwsgi出錯
plugins/python/uwsgi_python.h:2:20: fatal error: Python.h: No such file or directory
首先安裝python3環境
apt install python3-dev
然后再虛擬環境中
pip install uwsgi
66、xadmin后臺加載資料慢,解決方案
list_filter: 過濾器要慎用,不要使用類似id這些資料量大的欄位
class MallUserAdmin(object):
"""用戶管理"""
list_display = ['id', 'tp_icon', 'nickname', 'phone', 'level', 'balance', 'province', 'city', 'quxian'] # 顯示欄位
search_fields = ['id', 'nickname', 'phone'] # 搜索
list_filter = ['level', 'province', 'city', 'quxian'] # 過濾器
# list_filter = ['id', 'level', 'province', 'city', 'quxian'] # 如果加id,xadmin加載回來的資料就會很慢,所以不要在過濾器上使用id
list_per_page = 30 # 默認每頁數量
model_icon = 'fa fa-users' # 左側圖示
ordering = ['-id'] # 排序
readonly_fields = ['subscribe', 'wx_openid', 'phone'] # 只讀欄位
is_addbalance = True # 加載自定義的插件
relfield_style = 'fk-ajax' # 其他表如果外鍵到用戶表就做ajax搜索查詢,不一次性加載資料
67 、xadmin匯出插件處理,增加匯出勾選資料項
常規的匯出只有兩個選擇【匯出表頭】、【匯出全部資料】

現在想要做的是增加一個選擇,即【匯出表頭】、【匯出全部資料】、【匯出勾選資料】,如下圖:

需要修改xadmin源代碼,具體如下
1、加載js檔案
找到虛擬環境\Lib\site-packages\xadmin\views\list.py,在607行增加’xadmin.plugin.importexport.js’,如下圖所示

2、修改export.py,后端處理下載檔案
找到虛擬環境\Lib\site-packages\xadmin\plugins\export.py
在84行把rows = context[‘results’]修改成如下函式
# 新增匯出所選資料
# rows = context['results']
rows = []
select_across = self.request.GET.get('_select_across', False) == '1'
selected = self.request.GET.get('_selected_actions', '')
if self.request.GET.get('selected', 'off') == 'on':
if not select_across:
selected_pk = selected.split(',')
for i in context['results']:
if str(i['object'].id) in selected_pk:
rows.append(i)
else:
rows = context['results']
else:
rows = context['results']

3、 修改model_list.top_toolbar.exports.html
找到虛擬環境\Lib\site-packages\xadmin\templates\xadmin\blocks\model_list.top_toolbar.exports.html
使用以下代碼覆寫原檔案
{% load i18n %}
<div >
<a id="export-menu" data-toggle="dropdown" href="https://www.cnblogs.com/superwinner/archive/2023/01/15/#">
<i ></i> {% trans "Export" %} <span ></span>
</a>
<ul role="menu" aria-labelledby="dLabel">
{% for et in export_types %}
<li><a data-toggle="modal" data-target="#export-modal-{{et.type}}"><i >
</i> {% trans "Export" %} {{et.name}}</a></li>
{% endfor %}
</ul>
{% for et in export_types %}
<div id="export-modal-{{et.type}}" >
<div >
<div >
<form method="get" action="">
<div >
<button type="button" data-dismiss="modal" aria-hidden="true">×</button>
<h4 >{% trans "Export" %} {{et.name}}</h4>
</div>
<div >
{{ form_params|safe }}
<input type="hidden" name="export_type" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/{{et.type}}">
<!-- 增加 匯出所選資料 一欄 -->
<input type="hidden" name="_selected_actions" value=""/>
<input type="hidden" name="_select_across" value=""/>
<label >
{% if et.type == "xlsx" %}
<input type="checkbox" name="export_xlsx_header" checked="checked" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/on">
{% trans "Export with table header." %}
{% endif %}
{% if et.type == "xls" %}
<input type="checkbox" name="export_xls_header" checked="checked" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/on">
{% trans "Export with table header." %}
{% endif %}
{% if et.type == "csv" %}
<input type="checkbox" name="export_csv_header" checked="checked" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/on">
{% trans "Export with table header." %}
{% endif %}
{% if et.type == "xml" %}
<input type="checkbox" name="export_xml_format" checked="checked" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/on">
{% trans "Export with format." %}
{% endif %}
{% if et.type == "json" %}
<input type="checkbox" name="export_json_format" checked="checked" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/on">
{% trans "Export with format." %}
{% endif %}
</label>
<label >
<input type="checkbox" name="all" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/on"> {% trans "Export all data." %}
</label>
<!-- 增加 匯出所選資料 一欄 -->
<label >
<input type="checkbox" name="selected" value="https://www.cnblogs.com/superwinner/archive/2023/01/15/on"> 匯出勾選資料
</label>
</div>
<div >
<button type="button" data-dismiss="modal">{% trans "Close" %}</button>
<button type="submit"><i
></i> {% trans "Export" %}
</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dalog -->
</div><!-- /.modal -->
{% endfor %}
</div>
<script type="text/javascript">
// 如果是訂單匯出,把待出貨訂單設定成待識訓訂單
$(document).ready(function () {
$('.myexport').click(function () {
// 當把訂單匯出時,需要修改訂單狀態為待識訓狀態
var url = window.location.protocol + '//' + window.location.host + "/exportorder/";
$("input[name='_select_across']").val($("input[name='select_across']").val());
if ($("input[name='selected']").is(':checked')) {
var arr = [];
$.each($('.action-select'), function () {
if (true == $(this).prop('checked')) {
arr.push($(this).val());
}
});
if(arr.length == 0){
alert('請先勾選匯出資料')
return false
}
}else{
var arr = []
var order_type = $('.breadcrumb li').eq(1).text().trim()
$('.grid-item').each(function (index, el) {
arr.push($(el).find('td').eq(1).text().trim())
})
}
if (($('.breadcrumb > li').eq(1).text()).indexOf('訂單') != -1) {
// 5秒后執行
setTimeout(function () {
$.ajax({
type: "POST",
url: url,
data: {'orderlist': JSON.stringify(arr), 'order_type': order_type,},
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", $.getCookie("csrftoken"))
},
success: function (data) {
window.location.reload();
},
error: function (xhr) {
alert("出現未知錯誤");
window.location.reload();
}
});
}, 5000);
}
});
})
</script>
68、使用F查詢更新用戶重要資料
from django.db.models import F
# 使用F查詢更新用戶余額
balance = 5
MallUser.objects.filter(id=1).update(balance=F('balance') + balance)
相當于sql的
update Malluser set balance=balance + 5 where id=1;
69、日志輸出模塊
import logging
import platform
# 全域函式
PlATFORM = platform.system()
if (PlATFORM == "Linux"):
# linux系統,檔案保存在var下
SERVER_LOG_PATH = '/var/mylog.log'
else:
# windows系統,檔案保存在D盤下
SERVER_LOG_PATH = 'D:\mylog.log'
# 定義一個logging的物件,命名為mylog
LOGGER = logging.getLogger('mylog')
# 設定級別為WARNING
LOGGER.setLevel(logging.WARNING)
# 創建一個handler,用于寫入日志檔案
fh = logging.FileHandler(SERVER_LOG_PATH, encoding='utf-8')
fh.setLevel(logging.WARNING)
# 定義handler的輸出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
# 給Logger添加handler
LOGGER.addHandler(fh)
# 不在控制臺顯示
LOGGER.propagate = False
70、字典排序
字典在記憶體中發布是無序的,當想對鍵值或者鍵名進行排序時可以先把字典轉成元組,這可以達到排序的目的,
score = {'小明': {'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90, },
'小紅': {'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59, },
'小黑': {'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70, },
'小白': {'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80, },
}
# 對姓名進行排序,即對鍵名進行排序
b = sorted(score.items(), key=lambda x: x[0], reverse=True)
show_str = ''
for info in b:
# print(info)
key, value = https://www.cnblogs.com/superwinner/archive/2023/01/15/info[0], info[1]
show_str +='姓名:{},平均分:{},成績:{}'.format(key,value['avg_score'], value) + '\r\n'
print('對姓名進行排序')
print(show_str)
# 對平均分進行排序
b = sorted(score.items(), key=lambda x: x[1]['avg_score'], reverse=True)
show_str = ''
for info in b:
# print(info)
key, value = https://www.cnblogs.com/superwinner/archive/2023/01/15/info[0], info[1]
show_str +='姓名:{},平均分:{},成績:{}'.format(key,value['avg_score'], value) + '\r\n'
print('對平均分進行排序')
print(show_str)
# 對英語成績進行排序
b = sorted(score.items(), key=lambda x: x[1]['English'], reverse=True)
show_str = ''
for info in b:
# print(info)
key, value = https://www.cnblogs.com/superwinner/archive/2023/01/15/info[0], info[1]
show_str +='姓名:{},平均分:{},成績:{}'.format(key,value['avg_score'], value) + '\r\n'
print('對英語成績進行排序')
print(show_str)
輸出:
對姓名進行排序
姓名:小黑,平均分:70,成績:{'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70}
姓名:小紅,平均分:60,成績:{'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59}
姓名:小白,平均分:80,成績:{'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80}
姓名:小明,平均分:90,成績:{'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90}
對平均分進行排序
姓名:小明,平均分:90,成績:{'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90}
姓名:小白,平均分:80,成績:{'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80}
姓名:小黑,平均分:70,成績:{'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70}
姓名:小紅,平均分:60,成績:{'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59}
對英語成績進行排序
姓名:小白,平均分:80,成績:{'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80}
姓名:小明,平均分:90,成績:{'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90}
姓名:小黑,平均分:70,成績:{'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70}
姓名:小紅,平均分:60,成績:{'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59}
對串列中字典按多個鍵值排序
from operator import itemgetter
data = https://www.cnblogs.com/superwinner/archive/2023/01/15/[
{'code': 1, 'position': 300, 'time': '1620442242'},
{'code': 2, 'position': 255, 'time': '1620442242'},
{'code': 3, 'position': 256, 'time': '1620442242'},
{'code': 1, 'position': 500, 'time': '1620442242'},
{'code': 5, 'position': 455, 'time': '1620442242'},
{'code': 1, 'position': 322, 'time': '1620442242'},
{'code': 6, 'position': 676, 'time': '1620442242'},
]
data = https://www.cnblogs.com/superwinner/archive/2023/01/15/sorted(data, key=itemgetter('code', 'position'))
print(data)
輸出:
[
{'code': 1, 'position': 300, 'time': '1620442242'},
{'code': 1, 'position': 322, 'time': '1620442242'},
{'code': 1, 'position': 500, 'time': '1620442242'},
{'code': 2, 'position': 255, 'time': '1620442242'},
{'code': 3, 'position': 256, 'time': '1620442242'},
{'code': 5, 'position': 455, 'time': '1620442242'},
{'code': 6, 'position': 676, 'time': '1620442242'}]
71、時間格式與字串互轉、比較大小
import datetime
# 當前時間轉字串
now = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
# 字串轉時間格式
now = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
a = now + datetime.timedelta(minutes=-15)
# 時間比較大小
if a < now:
print('yes')
72、python把’\u’開頭的字串轉中文
str_data = 'https://www.cnblogs.com//u7528//u6237 ID //u6216//u5bc6//u7801//u9519//u8bef'
# 字串.encode('utf-8').decode('unicode_escape')
str_data_to_zh = str_data.encode('utf-8').decode('unicode_escape')
print(str_data_to_zh)
# 輸出
用戶 ID 或密碼錯誤
73、django進行資料遷移時出現No changes detected解決方案
原因:可能是由于app下面沒有migrations檔案夾
所以需要創建這個檔案夾,命令
python manage.py makemigrations --empty 你的app名稱
74、ubuntu下載檔案到windows桌面
apt install lrzsz
sz 123.txt
75、git查看提交日志
git log --author="ldc"
76、python翻譯模塊
可以把英文翻譯成中文,也可以把中文翻譯成英文
pip install translate
from translate import Translator
name = 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca'
translator = Translator(to_lang="chinese")
translation = translator.translate(name)
print(translation)
translator= Translator(from_lang="chinese",to_lang="english")
translation = translator.translate("我想你")
print(translation)
輸出:
大熊貓,熊貓,熊貓熊,浣熊,大熊貓
I missed you.
77、python實作字串轉字典
import ast
import json
target_str = '{"h": 1, "e": 2, "l": 3, "l": 4, "o": 5}'
target_str2 = "{'h': 1, 'e': 2, 'l': 3, 'l': 4, 'o': 5}"
# 方式1:使用json,缺點,字串中不能出現單引號
# 由于 json 語法規定 陣列或物件之中的字串必須使用雙引號,不能使用單引號
# 官網https://www.json.org/json-en.html上有一段描述是
# A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes
print(json.loads(target_str))
# print(json.loads(target_str2)) # 使用json轉這個字串會報錯 Expecting property name enclosed in double quotes
# 方式2:使用eval函式,缺點,不安全
print(eval(target_str))
print(eval(target_str2))
# print(eval("__import__('os').system('dir')")) # 會列出當前的目錄檔案,如果字串是一些洗掉命令,則可以把整個目錄清空!
# 方式3,使用ast.literal_eval,沒有json與eval的缺點,推薦使用這個
print(ast.literal_eval(target_str))
print(ast.literal_eval(target_str2))
輸出:
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
78、django app 如何在后臺顯示中文名
1.在app (這里以user為例)下面的__init__.py檔案中
添加:
default_app_config = 'user.apps.UserConfig'
2.在apps.py中
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'user'
verbose_name = '用戶'
79、使用python給Excel指定行添加資料
import openpyxl, sys
wb = openpyxl.load_workbook('b.xlsx')
sheet = wb['Sheet1']
# 在excel表格第二行添加新資料
addrow = 1 # 增加一行
row = 2 # 在第二行新增一行
name = 'b-back.xlsx' # 新的表名
wb1 = openpyxl.Workbook()
sheet1 = wb1['Sheet']
# 復制前row行
for i in range(1, row):
for j in range(1, sheet.max_column + 1):
sheet1.cell(row=i, column=j).value = https://www.cnblogs.com/superwinner/archive/2023/01/15/sheet.cell(row=i, column=j).value
# 復制后row行
for i in range(row, sheet.max_row + 1):
for j in range(1, sheet.max_column + 1):
if i == row:
# 給第row行添加新的資料
sheet1.cell(row=row, column=j).value ='新增'
sheet1.cell(row=i + addrow, column=j).value = https://www.cnblogs.com/superwinner/archive/2023/01/15/sheet.cell(row=i, column=j).value
wb1.save(name)

80、python中的format格式拼接字串
d = {'a': 1, 'b': 2, 'c': 3, 'd': 5}
print('{a},{b}'.format(**d))
print('{0},{1},{0}'.format('a', 'b'))
print(f"{d['a']}")
輸出:
1,2
a,b,a
1
81、資料庫inner join、full join、left join、union、union all區別
表a_test

表b_test

INNER JOIN
是A和B的交集
SELECT * FROM a_test INNER JOIN b_test ON a_test.name = b_test.namesa
Inner join 產生的結果集中,是A和B的交集,

FULL OUTER JOIN
產生A和B的并集
SELECT * FROM a_test FULL OUTER JOIN b_test ON a_test.name = b_test.name
Full outer join 產生A和B的并集,
但是需要注意的是,對于沒有匹配的記錄,則會以null做為值,
可以使用IF NULL判斷,

SELECT * FROM a_test FULL OUTER JOIN b_test ON a_test.name = b_test.name
WHERE a_test.id IS null OR b_test.id IS null
產生A表和B表沒有交集的資料集,

LEFT [OUTER] JOIN
產生表A的完全集,而B表中匹配的則有值,沒有匹配的則以null值取代
SELECT * FROM a_test LEFT OUTER JOIN b_test ON a_test.name = b_test.name
有些資料庫可以不要OUTER
SELECT * FROM a_test LEFT JOIN b_test ON a_test.name = b_test.name
Left outer join 產生表A的完全集,而B表中匹配的則有值,沒有匹配的則以null值取代,

SELECT * FROM a_test LEFT OUTER JOIN b_test ON a_test.name = b_test.name
WHERE b_test.id IS null
產生在A表中有而在B表中沒有的集合,

RIGHT [OUTER] JOIN
RIGHT OUTER JOIN 是后面的表為基礎,與LEFT OUTER JOIN用法類似,
UNION 與 UNION ALL
UNION 運算子用于合并兩個或多個 SELECT 陳述句的結果集,
請注意,UNION 內部的 SELECT 陳述句必須擁有相同數量的列,
列也必須擁有相似的資料型別,
同時,每條 SELECT 陳述句中的列的順序必須相同,
UNION 只選取記錄,而UNION ALL會列出所有記錄,
SELECT name FROM a_test UNION SELECT name FROM b_test
選取不同值

SELECT a_test.id,a_test.name FROM a_test
UNION
SELECT b_test.id,b_test.name FROM b_test
由于 id 51 xh 與 id 4 xh 并不相同,不合并

SELECT name FROM a_test UNION ALL SELECT name FROM b_test
全部列出來

還需要注意的是我們還有一個是“交差集” cross join, 這種Join沒有辦法用文式圖表示,因為其就是把表A和表B的資料進行一個N*M的組合,即笛卡爾積,
運算式如下:SELECT * FROM a_test CROSS JOIN b_test
這個笛卡爾乘積會產生 4 x 4 = 16 條記錄,一般來說,我們很少用到這個語法,但是我們得小心,如果不是使用嵌套的select陳述句,一般系統都會產生笛卡爾乘積然再做過濾,這是對于性能來說是非常危險的,尤其是表很大的時候,
82、windows電腦查看埠使用情況
找出8000埠對應的PID行程,命令為:
netstat -ano|findstr 8000
行程資訊如下:
TCP 0.0.0.0:8000 0.0.0.0:0 LISTENING 1620
UDP 0.0.0.0:8000 *:* 1620
找出行程對應的詳細資訊:
tasklist |findstr 1620
KGService.exe 1620 Console 1 18,696 K
關行程:
taskkill /pid 1620 /F
查看程式占用記憶體
比如查看python占用運行記憶體
tasklist /fi "imagename eq python.exe"

83、Django生成表和反向生成Model
正向生成:
python manage.py makemigrations
python manage.py migrate
反向:
會根據設定的資料庫中的表在自動生成對應的Model代碼,并列印出來
python manage.py inspectdb
以直接將列印的代碼直接匯入到指定的Model檔案中
python manage.py inspectdb > models.py
84、windows的hosts檔案位置
C:\Windows\System32\drivers\etc\hosts
85、postgresql資料庫
# 如果表存在就先洗掉
drop table if exists student;
# 創建學生表
# id serial not null 表示id自增
# id integer not null 表示id不自增
create table student
(
id serial not null
constraint student_pk
primary key,
name varchar,
class_id integer,
height numeric,
weight numeric,
write_date timestamp
);
comment on table student is '學生表';
comment on column student.name is '名稱';
comment on column student.class_id is '班級ID';
comment on column student.height is '身高';
comment on column student.weight is '體重';
comment on column student.write_date is '修改時間';
alter table student
owner to odoo;
# 更新
update user set name='張三' where id=111
# 更新表a的欄位為表b的值
update account_invoice
set sale_order_id=so.id
from sale_order so
where account_invoice.origin=so.name
# 新增
insert into "user" (name,sex) values ('小明',1),('小紅', 0)
# 新增或更新
如果id沖突就更新
INSERT INTO student(id, name)
VALUES(12, '小明'),(13, '小紅')
ON conflict(id) DO UPDATE
SET name ='未知';
如果id沖突就什么也不做
INSERT INTO student(id, name)
VALUES(12, '小明'),(13, '小紅')
ON conflict(id) DO NOTHING;
# 把一個表中的資料插入到另一個表中
insert into 目標表名 (column1,column2,columnn) select value1,value2,valuen from 源表名
比如:
insert into student (name, classs_name,create_date) select student_name as name, class_name, now() from class_table;
# 獲取當前時間
now()
select now()
# 洗掉
DELETE FROM table_name [WHERE Clause]
# 增加欄位
alter table 表名 add column 列名 型別;
# 洗掉欄位
alter table 表名 dropcolumn 列名 ;
# postgresql資料庫查看表所有欄位
select * from information_schema.columns where table_schema='public' and table_name='表名';
# postgresql獲取所有表名
select tablename from pg_tables where schemaname='public'
# 對查詢結果按id降序顯示
select * from table_name order by id desc
# 對查詢結果按id升序顯示
select * from table_name order by id asc
# 轉義字符, 查找name中包含單引號的記錄
select * from student where name like E'%\'%';
# 查看表記錄總數
select relname as TABLE_NAME, reltuples as rowCounts from pg_class where relkind = 'r' and relnamespace = (select oid from pg_namespace where nspname='public') order by rowCounts desc;
# 將結果轉換為陣列
SELECT array(SELECT "name" FROM sale_order);
# 將陣列合并為字串
select array_to_string(array[1,2,3], ',')
# 聯合子集更新,把sale_order_line的name連接換行符,然后按id更新到表a_test中對應的name
update a_test set name=array_to_string(array(select name from sale_order_line where order_id=a_test.id),'<br/>');
# PostgreSQL合并查詢同一列的多條記錄,針對一對多,多對多欄位
比如表:
id name
1 小明
1 小紅 id name
1 小亮 --> 1 小明,小亮,小紅
2 小強 2 小強,小王
2 小王
SELECT
id, array_to_string(ARRAY(SELECT unnest(array_agg(name order by name desc))),',') AS all_name
FROM
student
GROUP BY id;
# case陳述句
case var
when condition1 then statement1
when condition2 then statement2
else statementn
end as new_name
比如:
select case name
when '小明' then 'xm'
when '小紅' then 'xh'
when '小剛' then 'xg'
else 'xw'
end as short_name
from student
# 臨時表、字串合并、型別轉換、時間格式轉換、當前時間
WITH TEMP AS (
SELECT CAST ( concat ( bam.account_period_code, '-01' ) AS TIMESTAMP )
AS account_period_time
FROM bi_account_move AS bam )
SELECT
account_period_time,
to_char(CURRENT_DATE,'yyyy-MM-dd hh24:MI:ss') as current_date,
to_char( account_period_time, 'yyyy' ) as year,
to_char( account_period_time, 'MM' ) as month,
to_char( account_period_time, 'dd' ) as day
FROM TEMP
比如:
account_period_time current_date year month day
2019-06-01 0:00:00 2020-06-24 00:00:00 2019 06 01
2019-06-01 0:00:00 2020-06-24 00:00:00 2019 06 01
# 多個字串拼接
select
concat('payment_', CAST(ap.id as varchar)) as line_key
from ap
# 將查詢所得結果集的某一欄位拼接成字串,默認的是逗號
select GROUP_CONCAT(id) from test where id>5;
結果為:
1,2,3,4,5,6,7
# 使用其他分隔符拼接
select GROUP_CONCAT(id separator '-') from test where id>5;
結果為:
1-2-3-4-5-6-7
# 多個臨時表
WITH temp_student AS ( SELECT ID, NAME, sex FROM student WHERE sex = TRUE ),
temp_class AS (
SELECT
ID,
NAME,
student_id,
teacher_id
FROM
the_class
),
temp_teacher AS (
SELECT
ID,
NAME,
age
FROM
teacher
)
SELECT
ts.NAME AS student_name,
tc.NAME AS class_name,
te.NAME AS teacher_name
from temp_student as ts
LEFT JOIN temp_class AS tc ON tc.student_id = ts.ID
LEFT JOIN teacher AS te ON te.id = tc.teacher_id
# null轉成有意義的值
select COALESCE(name, '') as name from a_test
意思就是如果name為null,就轉為空字串
# 字串截取
select SUBSTRING('abcd',1,2); -- result:ab 表示從下標從1開始,截取2個字符
# 使用 interval 時間相加減(+/-)
當前時間 + 10秒,
select to_char(now() + interval '10 second', 'yyyy-mm-dd hh24:mi:ss') as reqDate from account_period;
當前時間 - 10秒
select to_char(now() + interval '-10 second', 'yyyy-mm-dd hh24:mi:ss') as reqDate from account_period;
當前時間 + 10分,
select to_char(now() + interval '10 minute', 'yyyy-mm-dd hh24:mi:ss') as reqDate from account_period;
當前時間 + 10時,
select to_char(now() + interval '10 hour', 'yyyy-mm-dd hh24:mi:ss') as reqDate from account_period;
當前時間 + 10天,
select to_char(now() + interval '10 day', 'yyyy-mm-dd hh24:mi:ss') as reqDate from account_period;
當前時間 + 10年,
select to_char(now() + interval '10 year', 'yyyy-mm-dd hh24:mi:ss') as reqDate from account_period;
# UNION types numeric and text cannot be matched
NULL::NUMERIC
這個問題,是因為幾個sql組合在一起時,同一個欄位的值,遇到null時,需要進行型別轉換,
# 對行記錄定義行編號,使用函式ROW_NUMBER()
# 按分數進行降序,然后給行記錄標記行編號,可以作為排名來使用
select
ROW_NUMBER() OVER (ORDER BY score desc) AS sequence_number,
name,score
from
b_test
# 數字轉字串
select cast(123 as VARCHAR);
# 字串轉數字
select cast('123' as INTEGER);
86、python控制臺輸出帶顏色的文字方法
#格式: 設定顏色開始 :\033[顯示方式;前景色;背景色m
#說明:
前景色 背景色 顏色
---------------------------------------
30 40 黑色
31 41 紅色
32 42 綠色
33 43 黃色
34 44 藍色
35 45 紫紅色
36 46 青藍色
37 47 白色
顯示方式 意義
-------------------------
0 終端默認設定
1 高亮顯示
4 使用下劃線
5 閃爍
7 反白顯示
8 不可見
#例子:
\033[1;31;40m <!--1-高亮顯示 31-前景色紅色 40-背景色黑色-->
\033[0m <!--采用終端默認設定,即取消顏色設定-->
例子
print('紫紅字體 \033[1;35m hello world \033[0m!')
print('褐色背景綠色字體 \033[1;32;43m hello world \033[0m!')
print('\033[1;33;44mhello world\033[0m')

87、控制臺輸出白色方框
print('█')
88、xadmin后臺編輯多對多欄位
在models.py定義了多對多欄位,想要在編輯時可以靈活使用這個欄位的話,可以按以下方法設定:
modes.py
class Book(models.Model):
title = models.CharField(verbose_name="書名", max_length=32)
second_title = models.CharField(verbose_name="副標題", max_length=32, blank=True, null=True)
author = models.CharField(verbose_name="作者", max_length=32)
translator = models.CharField(verbose_name="譯者", max_length=32, blank=True, null=True)
intro = models.TextField(verbose_name="描述")
pic = models.FileField(verbose_name="封面圖片", max_length=64, upload_to='book_cover', null=True, blank=True)
tags = models.ManyToManyField(Tags, verbose_name='書籍標簽', blank=True)
prizes = models.ManyToManyField(Prizes, verbose_name='獲獎詳情', blank=True)
sump = models.IntegerField(verbose_name="收藏人數", default=0)
rate_num = models.IntegerField(verbose_name="評分人數", default=0)
num = models.IntegerField(verbose_name="瀏覽量", default=0)
published_time = models.DateField(blank=True, null=True, verbose_name='出版時間')
create_time = models.DateTimeField(auto_now_add=True, verbose_name='創建時間')
class Meta:
db_table = 'book'
verbose_name = "圖書"
verbose_name_plural = "圖書"
def __str__(self):
return self.title
adminx.py
# 書籍管理
class BookAdmin(object):
search_fields = ['title', 'author', 'intro'] # 檢索欄位
list_display = ['id', 'show_pic', 'title', 'second_title', 'author', 'translator', 'published_time', 'intro',
'tags', 'prizes', 'num', 'sump', 'rate_num'] # 要顯示的欄位
list_filter = ['published_time', 'tags', 'prizes'] # 分組過濾的欄位
ordering = ('id',) # 設定默認排序欄位,負號表示降序排序
list_per_page = 30 # 默認每頁顯示多少條記錄,默認是100條
model_icon = 'fa fa-book' # 左側小圖示
list_editable = ['title', 'author', 'intro', 'published_time'] # 可編輯欄位
style_fields = {'tags': 'm2m_transfer', 'prizes': 'm2m_transfer'} # 控制欄位的顯示樣式
filter_horizontal = ('tags', 'prizes') # 水平選擇編輯多對多欄位
重點是設定style_fields 和filter_horizontal ,效果:

89、Django后臺通過按鈕顯示TextField欄位內容
由于TextField欄位型別內容可能很長,在后臺顯示時很占螢屏位置,可以通過按鈕來控制顯示,代碼如下:
models.py中定義了一個TextField欄位型別:
class Prizes(models.Model):
name = models.CharField(max_length=32, verbose_name="獎項")
intro = models.TextField(blank=True, null=True, verbose_name='簡介')
class Meta:
db_table = 'prizes'
verbose_name = "獎項"
verbose_name_plural = "獎項"
def __str__(self):
return self.name
這里使用xadmin作為后臺管理框架,在adminx.py中代碼如下:
import xadmin
from django.utils.safestring import mark_safe
from xadmin import views
from .models import *
# 獎項管理
class PrizesAdmin(object):
search_fields = ['name'] # 檢索欄位
list_display = ['id', 'name', 'show_intro']
list_filter = ['name']
ordering = ('id',)
def show_intro(self, obj):
# 顯示簡介
if not obj.intro:
return mark_safe('')
if len(obj.intro) < 20:
return mark_safe(obj.intro)
short_id = f'{obj._meta.db_table}_short_text_{obj.id}'
short_text_len = len(obj.intro) // 4
short_text = obj.intro[:short_text_len] + '......'
detail_id = f'{obj._meta.db_table}_detail_text_{obj.id}'
detail_text = obj.intro
text = """<style type="text/css">
#%s,%s {padding:10px;border:1px solid green;}
</style>
<script type="text/javascript">
function openShutManager(oSourceObj,oTargetObj,shutAble,oOpenTip,oShutTip,oShortObj){
var sourceObj = typeof oSourceObj == "string" ? document.getElementById(oSourceObj) : oSourceObj;
var targetObj = typeof oTargetObj == "string" ? document.getElementById(oTargetObj) : oTargetObj;
var shortObj = typeof oShortObj == "string" ? document.getElementById(oShortObj) : oShortObj;
var openTip = oOpenTip || "";
var shutTip = oShutTip || "";
if(targetObj.style.display!="none"){
if(shutAble) return;
targetObj.style.display="none";
shortObj.style.display="block";
if(openTip && shutTip){
sourceObj.innerHTML = shutTip;
}
} else {
targetObj.style.display="block";
shortObj.style.display="none";
if(openTip && shutTip){
sourceObj.innerHTML = openTip;
}
}
}
</script>
<p id="%s">%s</p>
<p><a href="https://www.cnblogs.com/superwinner/archive/2023/01/15/###" οnclick="openShutManager(this,'%s',false,'點擊關閉','點擊展開','%s')">點擊展開</a></p>
<p id="%s" style="display:none">
%s
</p>
""" % (short_id, detail_id, short_id, short_text, detail_id, short_id, detail_id, detail_text)
return mark_safe(text)
show_intro.short_description = '描述'
注意:復制代碼后需要做如下修改:

一開始效果

點擊展開效果:
90、前端判斷上傳的檔案是否為圖片且限制大小為300kB
<!DOCTYPE html>
<html lang="en-us">
<body >
<input id="id_icon" name="icon" type="file" onchange="imgTypeSize('id_icon',300)"
<script type="text/javascript">
//判斷是否為圖片,若為圖片,判斷其大小是否大于0.3M
function imgTypeSize(FileId, maxsize) {
/*獲取圖片內容物件*/
var imgFile = document.getElementById(FileId).files[0];
if (imgFile.name == "") {
alert("請上傳頭像哦");
return false;
} else {
/*圖片型別正則驗證*/
var imgStr = /\.(jpg|jpeg|png|bmp|BMP|JPG|PNG|JPEG)$/;
if (!imgStr.test(imgFile.name)) {
alert("檔案不是圖片型別");
return false;
} else {
/*圖片大小*/
var imagSize = imgFile.size;
if (imagSize < (1024 * maxsize)) {
return true;
} else {
alert(imgFile.name + "大小不能超過" + maxsize + "kB");
document.getElementById(FileId).valuehttps://www.cnblogs.com/superwinner/archive/2023/01/15/= ""
return false;
}
}
}
}
</script>
</body>
</html>
91、form表單提交前驗證
<form action="" method="post" id="login-form" onsubmit="return toVaild()">
<input id="id_account" name="account" type="text" placeholder="賬號"/>
<input id="id_password" name="password" type="password" placeholder="密碼">
<form>
<script type="text/javascript">
document.getElementById('id_username').focus()
function toVaild() {
var account = document.getElementById("id_account").value;
var password = document.getElementById("id_password").value;
if (account == "" || password == "") {
alert("請輸入賬號和密碼");
return false;
} else {
return true;
}
}
</script>
92、有序字典
import collections
d1 = collections.OrderedDict() # 創建一個有序字典
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d1['d'] = 'D'
for k, v in d1.items():
print(k, v)
93、Python在Windows系統下實作TTS(文字轉語音)
匯入包:
pip install pypiwin32
import win32com.client
spk = win32com.client.Dispatch("SAPI.SpVoice")
spk.Speak(u"my name is ldc,what is your name")
spk.Speak(u"大家好")
94、定義一個簡單鬧鐘
# pip install pypiwin32 -i https://pypi.python.org/simple
import win32com.client
import time
import winsound
spk = win32com.client.Dispatch("SAPI.SpVoice")
# 定義鬧鐘時間
clocktime = [[19, 19], [11, 10], [12, 10], [18, 47]]
runinghour = 1 # 定義運行時間
times = runinghour * 3600 # 次數
print(times)
for i in range(1, times):
time_now = [time.localtime(time.time()).tm_hour, time.localtime(time.time()).tm_min]
if time_now in clocktime:
print(time_now)
winsound.Beep(1000, 1000)
spk.Speak(u"快去看下飯好了沒有?")
time.sleep(60) # 每分鐘對比一次時間
95、根據年月獲取當月天數
def get_month_days(year, month):
"""
根據年份,月份資訊顯示此月份天數
:param year: 年份:
:param month: 月份(1~12):
:return: 當月天數
"""
if month >12 or month <= 0:
return -1
if month == 2:
return 29 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 28
if month in (4, 6, 9, 11):
return 30
else:
return 31
a = '2020-04'.split('-')
year = int(a[0])
month = int(a[1])
print(get_month_days(year,month))
輸出:
30
96、Django獲取favicon.ico圖示
制作一個ico檔案,使用PS或者某些在線生成ico的網站
將此檔案命名為“favicon.ico”后放在static/下

在urls.py中定義路由:
from django.urls import path
from django.views.generic import RedirectView
urlpatterns = [
# 訪問favicon.ico 網站圖示
path("favicon.ico",RedirectView.as_view(url='static/favicon.ico')),
]
97、django 靜態檔案配置
settings.py
STATIC_URL = '/static/'
# 添加靜態資源路由地址
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# 使用python manage.py collectstatic收集靜態檔案時時使用STATIC_ROOT
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
urls.py
from django.urls import path, re_path
from django.views.generic import RedirectView
from django.views.static import serve
from '你的專案名稱' import settings
urlpatterns = [
path("favicon.ico",RedirectView.as_view(url='static/favicon.ico')),
re_path('static/(?P<path>.*)$', serve, {'document_root': settings.STATICFILES_DIRS[0]}),
]
98、django JsonResponse回傳中文時顯示unicode編碼(\u67e5\u8be2)
原因
這個unicode編碼,是python3默認回傳的編碼,
解決方案
JsonResponse里面有個引數json_dumps_params,設定為json_dumps_params={‘ensure_ascii’:False}即可,
data = https://www.cnblogs.com/superwinner/archive/2023/01/15/{'msg': '創建成功',}
return JsonResponse(data=https://www.cnblogs.com/superwinner/archive/2023/01/15/data, json_dumps_params={'ensure_ascii': False})
99、獲取當前時間月份的首日與最后一天
import calendar
def get_month_start_and_end(date=datetime.datetime.now()):
"""
獲取當前時間的月份首日與最后一天
:param date:
:return: (首日,最后一天)
"""
year, month = str(date).split('-')[0], str(date).split('-')[1]
end = calendar.monthrange(int(year), int(month))[1]
return f'{year}-{month}-01', f'{year}-{month}-{end}'
100、xadmin后臺批量操作
adminx.py
import xadmin
from django.db.models import Sum
from xadmin.plugins.actions import BaseActionView
class MyCountFeeAction(BaseActionView):
"""
用戶余額統計
"""
action_name = "countuserfee" #: 相當于這個 Action 的唯一標示, 盡量用比較針對性的名字
description = u'統計用戶總余額' #: 描述, 出現在 Action 選單中, 可以使用 ``%(verbose_name_plural)s`` 代替 Model 的名字.
model_perm = 'view' # 權限
def do_action(self, queryset):
all_balance = MallUser.objects.all().aggregate(Sum('balance'))
return HttpResponse(f'用戶總余額{all_balance}')
class UserAdmin(object):
"""用戶資訊管理"""
list_display = ['username', 'balance', 'status', 'addtime']
search_fields = ['username', ]
list_filter = ['status', 'addtime']
list_per_page = 30 # 默認每頁數量
model_icon = 'fa fa-user'
list_editable = ['status']
ordering = ['-addtime']
actions = [ MyCountFeeAction] # 添加批量選擇操作

101、xadmin過濾器外鍵顯示特定值(比如只能過濾自己與超級管理員定義的資料)
首先,修改xadmin原始碼,修改xadmin/filters.py,在401行,做如下修改,
把self.lookup_choices = field.get_choices(include_blank=False)
改為:
# 呼叫自定義的方法
if hasattr(model_admin, '{field}_choices'.format(field=field.name)):
self.lookup_choices = getattr(model_admin, '{field}_choices'.format(field=field.name))(field, request,params, model,model_admin,field_path)
else:
self.lookup_choices = field.get_choices(include_blank=False)
如圖:

然后,在adminx.py中定義過濾的方法:
import xadmin
from django.db.models import Q, Sum
from xadmin.plugins.actions import BaseActionView
class MeasurePointAdmin(object):
# search_fields = ['user__name', 'user__account'] # 檢索欄位
list_display = ['num', 'elevation', 'correct_num', 'cumulative_amount']
list_filter = ['user', 'is_default', 'create_time'] # 分組過濾的欄位
list_editable = ['num', 'elevation', 'correct_num', 'cumulative_amount']
ordering = ('id',) # 設定默認排序欄位,負號表示降序排序
list_per_page = 30 # 默認每頁顯示多少條記錄,默認是100條
model_icon = 'fa fa-users' # 左側小圖示
readonly_fields = ['user', 'is_default']
import_excel = True
actions = [MyCountFeeAction]
# 定義的函式名必須是 欄位名_choices
def user_choices(self, field, request, params, model, model_admin, field_path):
# 超級用戶不做控制
if self.request.user.is_superuser:
return field.get_choices(include_blank=False)
# 過濾器只顯示自己與超級管理員
user_lst = field.related_model._default_manager.filter(Q(id=self.request.user.id) | Q(is_superuser=True))
# 回傳格式 [('pk','標題'),]
return [(user.id, user.username) for user in user_lst]
效果:

102、Django中的CSRF區域禁用
為了避免沒有csrf token而產生的403的forbidden錯誤,可以使用csrf_exempt裝飾器來處理POST、GET請求的View, 這種方式是CSRF區域禁用,
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt)
def update_data(request):
if request.method == 'POST':
pass
elif request.method == 'GET':
pass
103、使用python命令創建django專案
創建django專案
方式一:直接打開pycharm創建,選擇file->new project->django
方式二:通過命令創建
先創建虛擬環境:python -m venv django_venv
然后匯入django庫:pip install django -i https://pypi.tuna.tsinghua.edu.cn/simple
最后使用命令創建:django-admin startproject my_django_project
104、 二維串列、二維陣列行求和與列求和
import pandas as pd
from functools import reduce
# 二維陣列,對列和行求和
a = [
['', 0, '', 1, 4.1],
['', 0, '', '', 4],
['123', 0, '', 3, 4, 6,7],
]
def aa(x, y):
x = 0 if isinstance(x, str) else x
y = 0 if isinstance(y, str) else y
return x + y
# 對行求和
row_sum = [reduce(aa, i) for i in a]
# 對列求和,只能處理相同長度的子元素
column_sum_1 = [reduce(aa, i) for i in zip(*a)]
# 對列求和,可以處理不同長度的子元素
column_sum_2 = list(dict(pd.DataFrame(a).fillna(0).apply(lambda x: '' if any(isinstance(d, str) for d in x) else round(x.sum(), 2))).values())
print('行求和:{}\r\n列求和(相同長度):{}\r\n列求和:{}'.format(row_sum, column_sum_1, column_sum_2))
輸出:
行求和:[5.1, 4, 20]
列求和(相同長度):[0, 0, 0, 4, 12.1]
列求和:['', 0, '', '', 12.1, 6.0, 7.0]
105、獲取時間字串的月份數
from datetime import datetime
def get_months(start_month_str, end_month_str):
'''
# 獲取時間字串中的月份數
:param start_month_str: 開始字串
:param end_month_str: 結束字串
:return: 月份數
'''
end_month_date = datetime.strptime(end_month_str, '%Y-%m')
start_month_date = datetime.strptime(start_month_str, '%Y-%m')
end_year, end_month = end_month_date.year, end_month_date.month
start_year, start_month = start_month_date.year, start_month_date.month
return (end_year - start_year) *12 + (end_month - start_month) + 1
end_month_str = '2021-02'
start_month_str = '2020-07'
print(get_months(start_month_str, end_month_str))
輸出:
8
106、字串不足補零
print('hello world'.zfill(15)) # 補0
print('hello world'.rjust(15)) # 右對齊,補空格
print('hello world'.ljust(15)) # 左對齊,補空格
輸出:
0000hello world
hello world
hello world
107、時間戳轉字串日期
import time
t1 = time.time()
print(t1)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t1)))
輸出:
1621741567.082192
2021-05-23 11:46:07
使用函式:
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
@contact: 微信 1257309054
@file: 時間戳轉日期.py
@time: 2022/6/27 17:16
@author: LDC
"""
import time
import datetime
# 正確10位長度的時間戳可精確到秒,11-14位長度則是包含了毫秒
def int_to_datetime(intValue):
if len(str(intValue)) == 10:
# 精確到秒
timeValue = https://www.cnblogs.com/superwinner/archive/2023/01/15/time.localtime(intValue)
tempDate = time.strftime("%Y-%m-%d %H:%M:%S", timeValue)
datetimeValue = https://www.cnblogs.com/superwinner/archive/2023/01/15/datetime.datetime.strptime(tempDate,"%Y-%m-%d %H:%M:%S")
elif 10 < len(str(intValue)) and len(str(intValue)) < 15:
# 精確到毫秒
k = len(str(intValue)) - 10
timetamp = datetime.datetime.fromtimestamp(intValue / (1 * 10 ** k))
datetimeValue = https://www.cnblogs.com/superwinner/archive/2023/01/15/timetamp.strftime("%Y-%m-%d %H:%M:%S.%f")
else:
return -1
return datetimeValue
time1 = 1656321420
time2 = 1656321086560
print(int_to_datetime(time1))
print(int_to_datetime(time2))
'''
輸出:
2022-06-27 17:17:00
2022-06-27 17:11:26.560000
'''
108、串列轉字串
a = [1,2,3]
print(','.join(map(str,a)))
輸出:
`1,2,3`
109、pip國內鏡像源
pip install 庫名 -i https://pypi.tuna.tsinghua.edu.cn/simple
清華:-i https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:-i http://mirrors.aliyun.com/pypi/simple/
中國科技大學 -i https://pypi.mirrors.ustc.edu.cn/simple/
華中理工大學:-i http://pypi.hustunique.com/
山東理工大學:-i http://pypi.sdutlinux.org/
豆瓣:-i http://pypi.douban.com/simple/
110、python把時間字串轉換成剛剛、1天前、3個月前、1年前
import datetime
import time
def date_interval(date_str):
'''
獲取時間間隔
1分鐘前,2分鐘前,10分鐘前,1小時前,2小時前,1天前,2天前,3天前,1個月前,3個月前,1年前,3年前
:param date_str: 時間字串
:return: 字串
'''
date_str = time.strptime(date_str, '%Y-%m-%d %H:%M:%S')
# 將時間元組轉換為時間戳
t = time.mktime(date_str)
# 當前時間
seconds = time.time() - t
years = int(seconds // (60 * 60 * 24 * 365))
if years:
return '{}年前'.format(years)
months = int(seconds // (60 * 60 * 24 * 30))
if months:
return '{}月前'.format(months)
days = int(seconds // (60 * 60 * 24))
if days:
return '{}天前'.format(days)
hours = int(seconds // (60 * 60))
if hours:
return '{}小時前'.format(hours)
minutes = int(seconds // (60))
if minutes:
return '{}分鐘前'.format(minutes)
return '剛剛'
if __name__ == '__main__':
date1 = '2019-07-10 15:27:51'
date2 = '2021-07-10 15:27:51'
date3 = '2021-08-10 15:27:51'
date4 = '2021-08-12 11:01:51'
date5 = datetime.datetime.now() + datetime.timedelta(seconds=-3)
date5 = date5.strftime('%Y-%m-%d %H:%M:%S')
print(date_interval(date1))
print(date_interval(date2))
print(date_interval(date3))
print(date_interval(date4))
print(date_interval(date5))
111、Django使用ORM執行sql陳述句
通過raw函式執行
alarm_datas = gsm.AlertMessage.objects.raw('''
select am_all.id, am_all.sensor_number
FROM alert_message as am_all
where
am_all.real='1'
and am_all.is_show=1
order by am_all.alarm_level desc
''')
for ad in alarm_datas:
print(ad.sensor_number)
112、Django通過變數欄位獲取資料
通過方法__getattribute__來獲取
alert_messages = AlertMessage.objects.filter(real=0)
am_fields = ['id', 'real', 'name']
for am in alert_messages:
for i in range(len(am_fields)):
print(am_fields[i], am.__getattribute__(am_fields[i]))
113、Django查詢變數欄位、更新變數欄位
通過**{變數名:值}來操作
field = 'device_code'
# 查詢
device_infos = gsm.DeviceInfo.objects.filter(**{field: '012'})
# 更新
gsm.DeviceInfo.objects.filter(device_code='012').update(**{field : '0'})
114、vue生成dist檔案
安裝npm,到官網下載
在vue專案下打開cmd,輸入命令
npm run build
如果報錯,npm ERR! missing script: build,
則使用以下命令
npm run build:prod
具體看package.json

115、python獲取電腦磁盤、CPU、記憶體使用情況
import psutil
# pip install psutil
# 獲取本機磁盤使用率和剩余空間G資訊
def get_disk_info():
# 回圈磁盤磁區
content = ""
for disk in psutil.disk_partitions():
# 讀寫方式 光碟 or 有效磁盤型別
if 'cdrom' in disk.opts or disk.fstype == '':
continue
disk_name_arr = disk.device.split(':')
disk_name = disk_name_arr[0]
disk_info = psutil.disk_usage(disk.device)
# 磁盤剩余空間,單位G
free_disk_size = disk_info.free//1024//1024//1024
# 當前磁盤使用率和剩余空間G資訊
info = "{}盤使用率:{}%%, 剩余空間:{}G ".format(disk_name, str(disk_info.percent), free_disk_size)
# 拼接多個磁盤的資訊
content = content + info
print(content)
# cpu資訊
def get_cpu_info():
cpu_percent = psutil.cpu_percent(interval=1)
cpu_info = "CPU使用率:%i%%" % cpu_percent
print(cpu_info)
# 記憶體資訊
def get_memory_info():
virtual_memory = psutil.virtual_memory()
used_memory = virtual_memory.used/1024/1024/1024
free_memory = virtual_memory.free/1024/1024/1024
memory_percent = virtual_memory.percent
memory_info = "記憶體使用:%0.2fG,使用率%0.1f%%,剩余記憶體:%0.2fG" % (used_memory, memory_percent, free_memory)
print(memory_info)
if __name__ == '__main__':
get_disk_info()
get_cpu_info()
get_memory_info()
116、max比較字典串列
'''
使用max函式比較字典串列物件
需求:找出用戶組最大id的字典
'''
def com_id(f):
'''
比較用用戶ids串列
:param f: 字典
:return: 回傳最大的用戶id
'''
return max(f['user_ids'])
friends_added = [
{'user_ids': [1, 2], 'create_at': '2020-01-01'},
{'user_ids': [3, 6], 'create_at': '2020-01-02'},
{'user_ids': [2, 1], 'create_at': '2020-02-02'},
{'user_ids': [4, 1], 'create_at': '2020-02-02'},
]
# max函式中使用key引數,指定自定義函式來比較
item = max(friends_added, key=com_id)
item_1 = max(friends_added, key=lambda f: max(f['user_ids'])) # com_id可以轉成lambda函式
print(item)
print(item_1)
輸出:
{'user_ids': [3, 6], 'create_at': '2020-01-02'}
{'user_ids': [3, 6], 'create_at': '2020-01-02'}
117、django查詢表的具體欄位
ExampleModel.objects.values('id', 'username')
# 回傳的結果是QuerySet, 里面的元素是dict格式
# [{'id':1, 'username': 'Austin'}, {'id':2, 'username':'Sam'}, ...]
# 相當于SQL中的SELECT id, username FROM ......,
# 只回傳對應屬性(欄位)的值
118、MySQL查詢資料添加自增序號
set @i = 0;
select waveform, '沿橋風吹' as label ,(@i:=@i+1) xh from alert_message where is_real=1 and node_id=138
119、MySQL 時間截取年月日
select id,
addtime,
date_format(addtime,'%Y-%m-%d') as short_time
from alert_message
where date_format(addtime,'%Y-%m-%d') = '2022-03-13'

120、 串列取奇數下標值
list1=['a','b','c','d','e']
print('奇數下標值',list1[1::2])
輸出:
奇數下標值 ['b', 'd']
121、串列取偶數下標值
list1=['a','b','c','d','e']
print('偶數下標值',list1[::2])
偶數下標值 ['a', 'c', 'e']
122、串列相同元素分類、分組
import itertools
data = https://www.cnblogs.com/superwinner/archive/2023/01/15/[1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 1,'a', 'a']
a =[list(group) for key, group in itertools.groupby(data)]
print(a)
輸出:
[[1], [2, 2, 2, 2], [3, 3, 3], [4, 4, 4, 4], [1], ['a', 'a']]
123、ubuntu切換用戶
1)從user用戶切換到root用戶
sudo su
2)從root用戶切回user用戶
su user (user是你自己安裝時候的用戶名),或是直接輸入exit,也可Ctrl+D組合鍵推出
124、numpy二維陣列獲取某一列
import numpy as np
a = [
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13.2, 14.8, 15.9, 16.10, 16.11, 17.12],
]
a_np = np.array(a) # 把二維串列轉成numpy陣列
print('第一行', a_np[0].tolist()) # 獲取第一行
print('第一列', a_np[:, 0].tolist()) # 獲取第一列
輸出:
第一行 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
第一列 [1.0, 7.0, 13.2]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/542032.html
標籤:其他
上一篇:Netty(1)——NIO基礎
下一篇:Go語言學習筆記-1
