Python
Share
Flag
Related
Python generates random strings
There are two ways to generates random strings. The first one is to list all letters and numbers, and use random package.import random
base_str ='ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
p = random.sample(base_str, 5)
print(p)
>>>['S','P','G','Z','A'] The second method is to use string package directly.import string
value = ''.join(random.sample(string.ascii_letters + string.digits, 8))
print(value)
>>>PpvgJLmS
2024-05-12 00:56:04Django ImageField max_length error when uploading image
I'm using Django 4.2. I have a model whose fields containing ImageField, for example:class Example(models.Model)
image = models.ImageField(
blank=True,
upload_to=my_image_path,
)When I uploaded my image, I got this error from django: Ensure this filename has at most 100 characters (it has 107).Taken from the Django documentation:FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.And note that ImageField is a subclass of FileField:Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.ImageField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.Therefore, we just need to simply add max_length argument into the ImageField like ordinary CharField:class Example(models.Model)
image = models.ImageField(
blank=True,
upload_to=my_image_path,
max_length=500
)After this, don't forget to update it in your database:python manage.py makemigrations
python manage.py migrate
2024-06-07 22:05:31pyttsx3运行错误
接上文Python实现语音朗读,运行示例代码时import pyttsx3
engine = pyttsx3.init()
engine.say('开车不规范,亲人两行泪,I love China')
engine.runAndWait()弹出以下错误:经过检查,pywin32等库都已经安装好了。尝试使用win32com库替代pyttsx3,结果仍然报错,报错内容为win32 api。之后又尝试了几种办法,仍然都是跟win32有关的报错。因为之前pip安装总是SSL报错,刚开始以为是SSL报错导致安装出错。但是修复SSL报错问题后(见Python pip安装SSL证书错误),该问题仍然没解决。最后经过了解,可能是pywin32版本过高所导致。一般需要将pywin32版本控制在305以下,可以使用225或者226这样的低版本。于是使用pip下载对应版本pip install pypiwin32
pip install pywin32 == 225然而,下载时发现已经没有225版本可以下载。因此另寻办法。最终,发现是pywin32安装的版本有问题,导致包虽然有了,但是却无法识别,导致出现No module named 'win32gui'的报错。使用pip直接安装不行,就需要自己手动安装。在https://www.lfd.uci.edu/~gohlke/pythonlibs/中找到合适的pywin32版本下载后使用pip安装whl文件:pip install pywin32-304.0-cp311-cp311-win_amd64.whl安装成功后显示接下来,测试仅需要win32的代码import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("hello")成功运行!证明pywin32的问题已经解决。然而,继续运行import pyttsx3
engine = pyttsx3.init()
engine.say('开车不规范,亲人两行泪,I love China')
engine.runAndWait()仍然报错,不过报错的内容变了最后把C:\Python\Lib\site-packages\pywin32_system32中的文件pywintypes36.dll拷贝到目录C:\Python\Lib\site-packages\win32\lib下,成功运行pyttsx3的代码!
2024-06-08 20:38:00token简介以及python计算token的方法
后端登陆实现需要用到token机制或者cookies机制。Token和cookies都可以用来存放用户信息。但是token可以将信息存放在浏览器中的localstorage中,不占用服务器内存,而cookies则需要在每次请求中送往服务器中,吃服务器资源。同时,token作为一种比cookies更新的技术,有更多的优势,可以参考token和cookie的区别。每个用户都可以对应一个token值。Token可以由用户名+密码+时间,经过哈希加密得到,也可以直接由用户名和密码经过加密算法加密后得到。复杂程度取决于自己。加密后得到的token值,存放在会话session中。Python使用哈希算法进行加密,计算token值:import hashlib
md5 = hashlib.md5()
md5.update((username+password+"1258"+str(time.time())).encode())
token = md5.hexdigest()也可以使用python的pip库pyjwt来实现加密,计算token值。$ pip install pyjwtJwt输入的是字典型变量,以下为该函数的示例:>>> import jwt
>>> key = "secret"
>>> encoded = jwt.encode({"some": "payload"}, key, algorithm="HS256")
>>>print(encoded)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
>>> jwt.decode(encoded, key, algorithms="HS256")
{'some': 'payload'}关于pyjwt的更多用法,参考官方文档Usage Examples — PyJWT 2.8.0 documentation
2024-05-09 23:28:56Djano云服务器部署 uwsgi+nginx+https部署
Django启动服务器的命令runserver,其实也是启动了一个自带的uwsgi服务。如果想要一直在后台不停的运行django项目,需要部署uwsgi服务器。uwsgi安装官方文档:安装uWSGI — uWSGI 2.0 文档 (uwsgi-docs-zh.readthedocs.io)可以直接用pip安装uwsgi:pip install uwsgi在django项目根地址,即跟manage.py同目录下新建配置文件uwsgi.ini,如:mysite1/uwsgi.iniuwsgi.ini必须以[uwsgi]开头,内容如下:[uwsgi]
chdir=/mysite1
module=mysite1.wsgi:application
socket=127.0.0.1:8000
master=True
pidfile=uwsgi.pid
vacuum=True
max-requests=5000
daemonize=uwsgi.logchdir为django项目根地址,socket为django启动服务器的ip地址,daemonize为日志地址。注意,每个django项目中自动生成一个mysite1/wsgi.py文件。接下来cd 到 uWSGI 配置文件所在目录,执行以下代码即可:uwsgi --ini uwsgi.iniuWSGI的运行说明无论是启动还是关闭,都要执行ps aux|grep 'uwsgi’确认是否符合预期当uwsgi启动后,当前django项目的程序已变成后台守护进程,在关闭当前终端时此进程也不会停止启动成功后,进程在后台执行,所有日志均输出在配置文件所在目录的uwsgi.log中Django中代码有任何修改,都需要重启uwsgi(重启即为先关闭,再开启)配置好uwsgi服务后,还需要进一步配置nginx服务器,原因见为什么有了uwsgi 还要 nginx 服务器?和Nginx服务器反向代理。为了更高的加密性,我们可以使用nginx配置HTTPS协议。以下我们以腾讯云服务器为例,通过nginx配置HTTPS:首先找到/etc/nginx/conf.d,然后创建新文件django_nginx.confsudo vim django_nginx.conf接下来输入以下设置# 这种写法比较方便配合负载均衡
upstream backend {
# 这里的IP端口即Django项目的IP端口
server 127.0.0.1:8000;
# 如果uwsgi使用的本地文件,此处写法参考
# server unix:/path/to/your/mysite/mysite.sock;
}
server {
listen 443 ssl;
autoindex on;
client_max_body_size 1024m;
#请填写绑定证书的域名
server_name example.com;
#请填写证书文件的相对路径或绝对路径
ssl_certificate example.com_bundle.crt;
#请填写私钥文件的相对路径或绝对路径
ssl_certificate_key example.com.key;
ssl_session_timeout 5m;
#请按照以下协议配置
ssl_protocols TLSv1.2 TLSv1.3;
#请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location /static {
alias /path/to/your/mysite/static/;
}
location / {
include uwsgi_params;
uwsgi_pass backend;
}
}最后重新加载nginx,就大功告成啦!sudo nginx -s reload
2024-05-15 10:46:48为什么有了uwsgi 还要 nginx 服务器?
有关nginx的简单介绍,详见Nginx服务器反向代理。uwsgi是python的一个通信协议,同时也是一种web服务器,而nginx则是高性能反向代理的web服务器。在Django项目服务器部署中,uwsgi几乎是不可替代的。然而部署好了uwsgi,其实django接口已经能够响应请求,为什么还要额外配置nginx服务器?因为,相比于直接将真实地址暴露在公网上,在外面套一层nginx安全性更高,具体如下:安全问题,程序不能直接被浏览器访问到,而是通过nginx,nginx只开放某个接口,uwsgi本身是内网接口,这样运维人员在nginx上加上安全性的限制,可以达到保护程序的作用。负载均衡问题,一个uwsgi很可能不够用,即使开了多个work也是不行,毕竟一台机器的cpu和内存都是有限的,有了nginx做代理,一个nginx可以代理多台uwsgi完成uwsgi的负载均衡。静态文件处理效率问题,用django或是uwsgi这种东西来负责静态文件的处理是很浪费的行为,而且他们本身对文件的处理也不如nginx好,所以整个静态文件的处理都直接由nginx完成,静态文件的访问完全不去经过uwsgi以及其后面的东西。这就是这几者之间的关系。
2024-05-15 00:06:04Difference between time and datetime in python
Manipulating time is common during development. Python provides two packages from time, which are datetime and time. We will discuss the difference between the basic functions of these two packages.1. time :To get the current local time, first you need to run time.time() to get the current timestamp.import time
#Get the current timestamp
time.time()
#output: 1715254313.7382145Then you need to format the resulting timestamp to get your desirable time format, e.g. %Y-%m-%d %H:%M:%S.time.localtime(time.time())
#output: time.struct_time(tm_year=2024, tm_mon=5, tm_mday=9, tm_hour=19, tm_min=34, tm_sec=54, tm_wday=3, tm_yday=130, tm_isdst=0)
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
#output: '2024-05-09 19:37:54'It takes 5.5 seconds to run time.time() 100000000 times.start = time.time()
for _ in range(100000000):
pass
end = time.time()
print("%.2f seconds"%(end-start))
#output: 5.50 seconds2. datetime :To get the current local time, first you need to run datetime.datetime.now(), which outputs the current datetime object.import datetime
datetime.datetime.now()
#output: datetime.datetime(2024, 5, 9, 19, 43, 9, 36941)Then you could transform the resulting datetime object to string in your desirable format, e.g. %Y-%m-%d %H:%M:%S.datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#output: '2024-05-09 19:44:48'It takes 5 seconds to run datetime.datetime.now() 100000000 times.start = datetime.datetime.now()
while True:
for i in range(100000000):
pass
break
end = datetime.datetime.now()
print(str((end-start).seconds)+"seconds")
#output: 5 seconds
2024-05-09 19:55:13How to split views.py to several smaller files in Django
When your views.py is too large, it becomes much more difficult to manage your code. So you might want to split views.py into several subviews, each of which contains a single sort of views.To split views.py, you could follow the following steps. Your original views.py might look like this:import ...
def view1(request):
pass
def view2(request):
passNow, create a new folder subviews aside with views.py , i.e. /Django/mysite/MyAPI/subviews. Next, create __init__.py, viewsa.py, and viewsb.py in the folder subviews to form the following folder/file structure :subviews/
__init__.py
subviews1.py
subviews2.pysubviews1.py :from .views import *
def view1(request):
passsubviews2.py :from .views import *
def view2(request):
pass__init__.py :from subviews1 import *
from subviews2 import *Then this would work the same as a single views.py file. Don't forget to change the urls.py file before you reloading Django.
2024-05-01 14:11:30Django combine multiple QuerySets
Suppose that we have two different models.class Author(models.Model):
name = models.CharField(max_length=50)
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author)In certain circumstances, you might want to merge two querysets into one queryset. For example, you may want to combine Author.objects.all() and Article.objects.all(). You could accomplish this by pure python method itertools.chain, or using Django's inbuilt queryset method union . However, these are no more intuitive than combining two querysets directly.We recommend to use the package django-querysetsequence. To combine Author.objects.all() and Article.objects.all(), you just need to call QuerySetSequence directly :from queryset_sequence import QuerySetSequence
authors = Author.objects.all()
articles = Article.objects.all()
authors_articles = QuerySetSequence(authors, articles)If you have multiple models A, B, C, D, E, F , and have an array data containing their querysets, e.g. A.objects.all(), B.objects.all() , etc. To combine querysets in an array, you could make use of python's inbuilt method reduce :from functools import reduce
from queryset_sequence import QuerySetSequence
q = reduce(QuerySetSequence, data)
2024-05-03 00:33:49Django change an existing field to foreign key
I have a Django model that used to look like this:class Car(models.Model):
manufacturer_id = models.IntegerField()There is another model called Manufacturer that the id field refers to. However, I realized that it would be useful to use Django's built-in foreign key functionality, so I changed the model to this:class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer)This change appears to work fine immediately, queries work without errors, but when I try to run migrations, Django outputs the following:- Remove field manufacturer_id from car
- Add field manufacturer to carDoing this migration would clear all the existing relationships in the database, so I don't want to do that. I don't really want any migrations at all, since queries like Car.objects.get(manufacturer__name="Toyota") work fine. I would like a proper database foreign key constraint, but it's not a high priority.So my question is this: Is there a way to make a migration or something else that allows me to convert an existing field to a foreign key? I cannot use --fake since I need to reliably work across dev, prod, and my coworkers' computers.内容来源于 Stack Overflow, 遵循 CCBY-SA 4.0 许可协议进行翻译与使用。原文链接:Django change an existing field to foreign key
2024-08-17 16:03:04