python3.7下載地址html
Python安裝pippython
一、首先檢查linux有沒有安裝python-pip包,直接執行 yum install python-pipmysql
二、沒有python-pip包就執行命令 yum -y install epel-releasejquery
(3)、執行成功以後,再次執行yum install python-piplinux
(4)、對安裝好的pip進行升級 pip install --upgrade pipnginx
至此,pip工具就安裝好了。git
在python3.x以上的安裝過程當中,會自動詢問是否安裝pip等工具ajax
查看安裝了多少個模塊sql
pip list
Pycharm在建立py文件時,如何自動添加文件頭註釋數據庫
1.打開PyCharm程序,根據菜單欄中按照以下進入設置: 2.File -> settings -> Editor -> File and Code Templates -> Python Script 3.找到Python Script選項,而後將一下內容添加進文本框便可: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : ${DATE} ${TIME} # @Author : Aries # @Site : ${SITE} # @File : ${NAME}.py
# @Software: ${PRODUCT_NAME}
python中主流的模板模塊
jinja2:pip install jinja2 python -c "import jinja2" # 沒有報錯就表示安裝成功 # 必須用雙引號" 使用方法 https://www.cnblogs.com/dachenzi/p/8242713.html
python安裝第三方模塊報錯
cmd進入Python安裝路徑scripts文件夾
>pip install requests
報錯: Collecting requests Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),)': /simple/requests/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),)': /simple/requests/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),)': /simple/requests/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),)': /simple/requests/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),)': /simple/requests/ Could not fetch URL https://pypi.python.org/simple/requests/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/requests/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)'),)) - skipping Could not find a version that satisfies the requirement requests (from versions: )
緣由:查找網上的解釋是網速太慢,或被牆了。
解決辦法:使用國內鏡像加速。
>pip install requests -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
pymysql操做
https://blog.csdn.net/u013166622/article/details/50789945
python Ajax操做
https://www.cnblogs.com/wupeiqi/articles/6216618.html
python orm操做 參考
1.字段
AutoField(Field) - int自增列,必須填入參數 primary_key=True BigAutoField(AutoField) - bigint自增列,必須填入參數 primary_key=True 注:當model中若是沒有自增列,則自動會建立一個列名爲id的列 from django.db import models class UserInfo(models.Model): # 自動建立一個列名爲id的且爲自增的整數列 username = models.CharField(max_length=32) class Group(models.Model): # 自定義自增列 nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) SmallIntegerField(IntegerField): - 小整數 -32768 ~ 32767 PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField) - 正小整數 0 ~ 32767 IntegerField(Field) - 整數列(有符號的) -2147483648 ~ 2147483647 PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField) - 正整數 0 ~ 2147483647 BigIntegerField(IntegerField): - 長整型(有符號的) -9223372036854775808 ~ 9223372036854775807 BooleanField(Field) - 布爾值類型 NullBooleanField(Field): - 能夠爲空的布爾值 CharField(Field) - 字符類型 - 必須提供max_length參數, max_length表示字符長度 TextField(Field) - 文本類型 EmailField(CharField): - 字符串類型,Django Admin以及ModelForm中提供驗證機制 IPAddressField(Field) - 字符串類型,Django Admin以及ModelForm中提供驗證 IPV4 機制 GenericIPAddressField(Field) - 字符串類型,Django Admin以及ModelForm中提供驗證 Ipv4和Ipv6 - 參數: protocol,用於指定Ipv4或Ipv6, 'both',"ipv4","ipv6" unpack_ipv4, 若是指定爲True,則輸入::ffff:192.0.2.1時候,可解析爲192.0.2.1,開啓刺功能,須要protocol="both" URLField(CharField) - 字符串類型,Django Admin以及ModelForm中提供驗證 URL SlugField(CharField) - 字符串類型,Django Admin以及ModelForm中提供驗證支持 字母、數字、下劃線、鏈接符(減號) CommaSeparatedIntegerField(CharField) - 字符串類型,格式必須爲逗號分割的數字 UUIDField(Field) - 字符串類型,Django Admin以及ModelForm中提供對UUID格式的驗證 FilePathField(Field) - 字符串,Django Admin以及ModelForm中提供讀取文件夾下文件的功能 - 參數: path, 文件夾路徑 match=None, 正則匹配 recursive=False, 遞歸下面的文件夾 allow_files=True, 容許文件 allow_folders=False, 容許文件夾 FileField(Field) - 字符串,路徑保存在數據庫,文件上傳到指定目錄 - 參數: upload_to = "" 上傳文件的保存路徑 storage = None 存儲組件,默認django.core.files.storage.FileSystemStorage ImageField(FileField) - 字符串,路徑保存在數據庫,文件上傳到指定目錄 - 參數: upload_to = "" 上傳文件的保存路徑 storage = None 存儲組件,默認django.core.files.storage.FileSystemStorage width_field=None, 上傳圖片的高度保存的數據庫字段名(字符串) height_field=None 上傳圖片的寬度保存的數據庫字段名(字符串) DateTimeField(DateField) - 日期+時間格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] DateField(DateTimeCheckMixin, Field) - 日期格式 YYYY-MM-DD TimeField(DateTimeCheckMixin, Field) - 時間格式 HH:MM[:ss[.uuuuuu]] DurationField(Field) - 長整數,時間間隔,數據庫中按照bigint存儲,ORM中獲取的值爲datetime.timedelta類型 FloatField(Field) - 浮點型 DecimalField(Field) - 10進制小數 - 參數: max_digits,小數總長度 decimal_places,小數位長度 BinaryField(Field) - 二進制類型 字段列表
class UnsignedIntegerField(models.IntegerField): def db_type(self, connection): return 'integer UNSIGNED' PS: 返回值爲字段在數據庫中的屬性,Django字段默認的值爲: 'AutoField': 'integer AUTO_INCREMENT', 'BigAutoField': 'bigint AUTO_INCREMENT', 'BinaryField': 'longblob', 'BooleanField': 'bool', 'CharField': 'varchar(%(max_length)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)', 'DateField': 'date', 'DateTimeField': 'datetime', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'DurationField': 'bigint', 'FileField': 'varchar(%(max_length)s)', 'FilePathField': 'varchar(%(max_length)s)', 'FloatField': 'double precision', 'IntegerField': 'integer', 'BigIntegerField': 'bigint', 'IPAddressField': 'char(15)', 'GenericIPAddressField': 'char(39)', 'NullBooleanField': 'bool', 'OneToOneField': 'integer', 'PositiveIntegerField': 'integer UNSIGNED', 'PositiveSmallIntegerField': 'smallint UNSIGNED', 'SlugField': 'varchar(%(max_length)s)', 'SmallIntegerField': 'smallint', 'TextField': 'longtext', 'TimeField': 'time', 'UUIDField': 'char(32)',
1.觸發Model中的驗證和錯誤提示有兩種方式: a. Django Admin中的錯誤信息會優先根據Admiin內部的ModelForm錯誤信息提示,若是都成功,纔來檢查Model的字段並顯示指定錯誤信息 b. 使用ModelForm c. 調用Model對象的 clean_fields 方法,如: # models.py class UserInfo(models.Model): nid = models.AutoField(primary_key=True) username = models.CharField(max_length=32) email = models.EmailField(error_messages={'invalid': '格式錯了.'}) # views.py def index(request): obj = models.UserInfo(username='11234', email='uu') try: print(obj.clean_fields()) except Exception as e: print(e) return HttpResponse('ok') # Model的clean方法是一個鉤子,可用於定製操做,如:上述的異常處理。 2.Admin中修改錯誤提示 # admin.py from django.contrib import admin from model_club import models from django import forms class UserInfoForm(forms.ModelForm): age = forms.IntegerField(initial=1, error_messages={'required': '請輸入數值.', 'invalid': '年齡必須爲數值.'}) class Meta: model = models.UserInfo # fields = ('username',) fields = "__all__" exclude = ['title'] labels = { 'name':'Writer', } help_texts = {'name':'some useful help text.',} error_messages={ 'name':{'max_length':"this writer name is too long"} } widgets={'name':Textarea(attrs={'cols':80,'rows':20})} class UserInfoAdmin(admin.ModelAdmin): form = UserInfoForm admin.site.register(models.UserInfo, UserInfoAdmin)
2.參數字段
null 數據庫中字段是否能夠爲空 db_column 數據庫中字段的列名 default 數據庫中字段的默認值 primary_key 數據庫中字段是否爲主鍵 db_index 數據庫中字段是否能夠創建索引 unique 數據庫中字段是否能夠創建惟一索引 unique_for_date 數據庫中字段【日期】部分是否能夠創建惟一索引 unique_for_month 數據庫中字段【月】部分是否能夠創建惟一索引 unique_for_year 數據庫中字段【年】部分是否能夠創建惟一索引 verbose_name Admin中顯示的字段名稱 blank Admin中是否容許用戶輸入爲空 editable Admin中是否能夠編輯 help_text Admin中該字段的提示信息 choices Admin中顯示選擇框的內容,用不變更的數據放在內存中從而避免跨表操做 如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1) error_messages 自定義錯誤信息(字典類型),從而定製想要顯示的錯誤信息; 字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date 如:{'null': "不能爲空.", 'invalid': '格式錯誤'} validators 自定義錯誤驗證(列表類型),從而定製想要的驗證規則 from django.core.validators import RegexValidator from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\ MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator 如: test = models.CharField( max_length=32, error_messages={ 'c1': '優先錯信息1', 'c2': '優先錯信息2', 'c3': '優先錯信息3', }, validators=[ RegexValidator(regex='root_\d+', message='錯誤了', code='c1'), RegexValidator(regex='root_112233\d+', message='又錯誤了', code='c2'), EmailValidator(message='又錯誤了', code='c3'), ] )
3.元信息
class UserInfo(models.Model): nid = models.AutoField(primary_key=True) username = models.CharField(max_length=32) class Meta: # 數據庫中生成的表名稱 默認 app名稱 + 下劃線 + 類名 db_table = "table_name" # 聯合索引 index_together = [ ("pub_date", "deadline"), ] # 聯合惟一索引 unique_together = (("driver", "restaurant"),) # admin中顯示的表名稱 verbose_name # verbose_name加s verbose_name_plural
更多:https://docs.djangoproject.com/en/1.10/ref/models/options/
4.多表以及參數
ForeignKey(ForeignObject) # ForeignObject(RelatedField) to, # 要進行關聯的表名 to_field=None, # 要關聯的表中的字段名稱 on_delete=None, # 當刪除關聯表中的數據時,當前表與其關聯的行的行爲 - models.CASCADE,刪除關聯數據,與之關聯也刪除 - models.DO_NOTHING,刪除關聯數據,引起錯誤IntegrityError - models.PROTECT,刪除關聯數據,引起錯誤ProtectedError - models.SET_NULL,刪除關聯數據,與之關聯的值設置爲null(前提FK字段須要設置爲可空) - models.SET_DEFAULT,刪除關聯數據,與之關聯的值設置爲默認值(前提FK字段須要設置默認值) - models.SET,刪除關聯數據, a. 與之關聯的值設置爲指定值,設置:models.SET(值) b. 與之關聯的值設置爲可執行對象的返回值,設置:models.SET(可執行對象) def func(): return 10 class MyModel(models.Model): user = models.ForeignKey( to="User", to_field="id" on_delete=models.SET(func),) related_name=None, # 反向操做時,使用的字段名,用於代替 【表名_set】 如: obj.表名_set.all() related_query_name=None, # 反向操做時,使用的鏈接前綴,用於替換【表名】 如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名') limit_choices_to=None, # 在Admin或ModelForm中顯示關聯數據時,提供的條件: # 如: - limit_choices_to={'nid__gt': 5} - limit_choices_to=lambda : {'nid__gt': 5} from django.db.models import Q - limit_choices_to=Q(nid__gt=10) - limit_choices_to=Q(nid=8) | Q(nid__gt=10) - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root') db_constraint=True # 是否在數據庫中建立外鍵約束 parent_link=False # 在Admin中是否顯示關聯數據 OneToOneField(ForeignKey) to, # 要進行關聯的表名 to_field=None # 要關聯的表中的字段名稱 on_delete=None, # 當刪除關聯表中的數據時,當前表與其關聯的行的行爲 ###### 對於一對一 ###### # 1. 一對一其實就是 一對多 + 惟一索引 # 2.當兩個類之間有繼承關係時,默認會建立一個一對一字段 # 以下會在A表中額外增長一個c_ptr_id列且惟一: class C(models.Model): nid = models.AutoField(primary_key=True) part = models.CharField(max_length=12) class A(C): id = models.AutoField(primary_key=True) code = models.CharField(max_length=1) ManyToManyField(RelatedField) to, # 要進行關聯的表名 related_name=None, # 反向操做時,使用的字段名,用於代替 【表名_set】 如: obj.表名_set.all() related_query_name=None, # 反向操做時,使用的鏈接前綴,用於替換【表名】 如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名') limit_choices_to=None, # 在Admin或ModelForm中顯示關聯數據時,提供的條件: # 如: - limit_choices_to={'nid__gt': 5} - limit_choices_to=lambda : {'nid__gt': 5} from django.db.models import Q - limit_choices_to=Q(nid__gt=10) - limit_choices_to=Q(nid=8) | Q(nid__gt=10) - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root') symmetrical=None, # 僅用於多對多自關聯時,symmetrical用於指定內部是否建立反向操做的字段 # 作以下操做時,不一樣的symmetrical會有不一樣的可選字段 models.BB.objects.filter(...) # 可選字段有:code, id, m1 class BB(models.Model): code = models.CharField(max_length=12) m1 = models.ManyToManyField('self',symmetrical=True) # 可選字段有: bb, code, id, m1 class BB(models.Model): code = models.CharField(max_length=12) m1 = models.ManyToManyField('self',symmetrical=False) through=None, # 自定義第三張表時,使用字段用於指定關係表 through_fields=None, # 自定義第三張表時,使用字段用於指定關係表中那些字段作多對多關係表 from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64) db_constraint=True, # 是否在數據庫中建立外鍵約束 db_table=None, # 默認建立第三張表時,數據庫中表的名稱
5.orm操做
# 增 # # models.Tb1.objects.create(c1='xx', c2='oo') 增長一條數據,能夠接受字典類型數據 **kwargs # obj = models.Tb1(c1='xx', c2='oo') # obj.save() # 查 # # models.Tb1.objects.get(id=123) # 獲取單條數據,不存在則報錯(不建議) # models.Tb1.objects.all() # 獲取所有 # models.Tb1.objects.filter(name='seven') # 獲取指定條件的數據 # models.Tb1.objects.exclude(name='seven') # 獲取指定條件的數據 # 刪 # # models.Tb1.objects.filter(name='seven').delete() # 刪除指定條件的數據 # 改 # models.Tb1.objects.filter(name='seven').update(gender='0') # 將指定條件的數據更新,均支持 **kwargs # obj = models.Tb1.objects.get(id=1) # obj.c1 = '111' # obj.save() # 修改單條數據
# 獲取個數 # # models.Tb1.objects.filter(name='seven').count() # 大於,小於 # # models.Tb1.objects.filter(id__gt=1) # 獲取id大於1的值 # models.Tb1.objects.filter(id__gte=1) # 獲取id大於等於1的值 # models.Tb1.objects.filter(id__lt=10) # 獲取id小於10的值 # models.Tb1.objects.filter(id__lte=10) # 獲取id小於10的值 # models.Tb1.objects.filter(id__lt=10, id__gt=1) # 獲取id大於1 且 小於10的值 # in # # models.Tb1.objects.filter(id__in=[11, 22, 33]) # 獲取id等於十一、2二、33的數據 # models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in # isnull # Entry.objects.filter(pub_date__isnull=True) # contains # # models.Tb1.objects.filter(name__contains="ven") # models.Tb1.objects.filter(name__icontains="ven") # icontains大小寫不敏感 # models.Tb1.objects.exclude(name__icontains="ven") # range # # models.Tb1.objects.filter(id__range=[1, 2]) # 範圍bettwen and # 其餘相似 # # startswith,istartswith, endswith, iendswith, # order by # # models.Tb1.objects.filter(name='seven').order_by('id') # asc # models.Tb1.objects.filter(name='seven').order_by('-id') # desc # group by # # from django.db.models import Count, Min, Max, Sum # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num')) # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id" # limit 、offset # # models.Tb1.objects.all()[10:20] # regex正則匹配,iregex 不區分大小寫 # # Entry.objects.get(title__regex=r'^(An?|The) +') # Entry.objects.get(title__iregex=r'^(an?|the) +') # date # # Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1)) # Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1)) # year # # Entry.objects.filter(pub_date__year=2005) # Entry.objects.filter(pub_date__year__gte=2005) # month # # Entry.objects.filter(pub_date__month=12) # Entry.objects.filter(pub_date__month__gte=6) # day # # Entry.objects.filter(pub_date__day=3) # Entry.objects.filter(pub_date__day__gte=3) # week_day # # Entry.objects.filter(pub_date__week_day=2) # Entry.objects.filter(pub_date__week_day__gte=2) # hour # # Event.objects.filter(timestamp__hour=23) # Event.objects.filter(time__hour=5) # Event.objects.filter(timestamp__hour__gte=12) # minute # # Event.objects.filter(timestamp__minute=29) # Event.objects.filter(time__minute=46) # Event.objects.filter(timestamp__minute__gte=29) # second # # Event.objects.filter(timestamp__second=31) # Event.objects.filter(time__second=2) # Event.objects.filter(timestamp__second__gte=31)
# extra # # extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) # Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,)) # Entry.objects.extra(where=['headline=%s'], params=['Lennon']) # Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"]) # Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid']) # F # # from django.db.models import F # models.Tb1.objects.update(num=F('num')+1) # Q # # 方式一: # Q(nid__gt=10) # Q(nid=8) | Q(nid__gt=10) # Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root') # 方式二: # con = Q() # q1 = Q() # q1.connector = 'OR' # q1.children.append(('id', 1)) # q1.children.append(('id', 10)) # q1.children.append(('id', 9)) # q2 = Q() # q2.connector = 'OR' # q2.children.append(('c1', 1)) # q2.children.append(('c1', 10)) # q2.children.append(('c1', 9)) # con.add(q1, 'AND') # con.add(q2, 'AND') # # models.Tb1.objects.filter(con) # 執行原生SQL # # from django.db import connection, connections # cursor = connection.cursor() # cursor = connections['default'].cursor() # cursor.execute("""SELECT * from auth_user where id = %s""", [1]) # row = cursor.fetchone()
################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self) # 獲取全部的數據對象 def filter(self, *args, **kwargs) # 條件查詢 # 條件能夠是:參數,字典,Q def exclude(self, *args, **kwargs) # 條件查詢 # 條件能夠是:參數,字典,Q def select_related(self, *fields) 性能相關:表之間進行join連表操做,一次性獲取關聯的數據。 model.tb.objects.all().select_related() model.tb.objects.all().select_related('外鍵字段') model.tb.objects.all().select_related('外鍵字段__外鍵字段') def prefetch_related(self, *lookups) 性能相關:多表連表操做時速度會慢,使用其執行屢次SQL查詢在Python代碼中實現連表操做。 # 獲取全部用戶表 # 獲取用戶類型表where id in (用戶表中的查到的全部用戶ID) models.UserInfo.objects.prefetch_related('外鍵字段') from django.db.models import Count, Case, When, IntegerField Article.objects.annotate( numviews=Count(Case( When(readership__what_time__lt=treshold, then=1), output_field=CharField(), )) ) students = Student.objects.all().annotate(num_excused_absences=models.Sum( models.Case( models.When(absence__type='Excused', then=1), default=0, output_field=models.IntegerField() ))) def annotate(self, *args, **kwargs) # 用於實現聚合group by查詢 from django.db.models import Count, Avg, Max, Min, Sum v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')) # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')).filter(uid__gt=1) # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1 v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id',distinct=True)).filter(uid__gt=1) # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1 def distinct(self, *field_names) # 用於distinct去重 models.UserInfo.objects.values('nid').distinct() # select distinct nid from userinfo 注:只有在PostgreSQL中才能使用distinct進行去重 def order_by(self, *field_names) # 用於排序 models.UserInfo.objects.all().order_by('-id','age') def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) # 構造額外的查詢條件或者映射,如:子查詢 Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,)) Entry.objects.extra(where=['headline=%s'], params=['Lennon']) Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"]) Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid']) def reverse(self): # 倒序 models.UserInfo.objects.all().order_by('-nid').reverse() # 注:若是存在order_by,reverse則是倒序,若是多個排序則一一倒序 def defer(self, *fields): models.UserInfo.objects.defer('username','id') 或 models.UserInfo.objects.filter(...).defer('username','id') #映射中排除某列數據 def only(self, *fields): #僅取某個表中的數據 models.UserInfo.objects.only('username','id') 或 models.UserInfo.objects.filter(...).only('username','id') def using(self, alias): 指定使用的數據庫,參數爲別名(setting中的設置) ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=None, translations=None, using=None): # 執行原生SQL models.UserInfo.objects.raw('select * from userinfo') # 若是SQL是其餘表時,必須將名字設置爲當前UserInfo對象的主鍵列名 models.UserInfo.objects.raw('select id as nid from 其餘表') # 爲原生SQL設置參數 models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,]) # 將獲取的到列名轉換爲指定列名 name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'} Person.objects.raw('SELECT * FROM some_other_table', translations=name_map) # 指定數據庫 models.UserInfo.objects.raw('select * from userinfo', using="default") ################### 原生SQL ################### from django.db import connection, connections cursor = connection.cursor() # cursor = connections['default'].cursor() cursor.execute("""SELECT * from auth_user where id = %s""", [1]) row = cursor.fetchone() # fetchall()/fetchmany(..) def values(self, *fields): # 獲取每行數據爲字典格式 def values_list(self, *fields, **kwargs): # 獲取每行數據爲元祖 def dates(self, field_name, kind, order='ASC'): # 根據時間進行某一部分進行去重查找並截取指定內容 # kind只能是:"year"(年), "month"(年-月), "day"(年-月-日) # order只能是:"ASC" "DESC" # 並獲取轉換後的時間 - year : 年-01-01 - month: 年-月-01 - day : 年-月-日 models.DatePlus.objects.dates('ctime','day','DESC') def datetimes(self, field_name, kind, order='ASC', tzinfo=None): # 根據時間進行某一部分進行去重查找並截取指定內容,將時間轉換爲指定時區時間 # kind只能是 "year", "month", "day", "hour", "minute", "second" # order只能是:"ASC" "DESC" # tzinfo時區對象 models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.UTC) models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.timezone('Asia/Shanghai')) """ pip3 install pytz import pytz pytz.all_timezones pytz.timezone(‘Asia/Shanghai’) """ def none(self): # 空QuerySet對象 #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def aggregate(self, *args, **kwargs): # 聚合函數,獲取字典類型聚合結果 from django.db.models import Count, Avg, Max, Min, Sum result = models.UserInfo.objects.aggregate(k=Count('u_id', distinct=True), n=Count('nid')) ===> {'k': 3, 'n': 4} def count(self): # 獲取個數 def get(self, *args, **kwargs): # 獲取單個對象 def create(self, **kwargs): # 建立對象 def bulk_create(self, objs, batch_size=None): # 批量插入 # batch_size表示一次插入的個數 objs = [ models.DDD(name='r11'), models.DDD(name='r22') ] models.DDD.objects.bulk_create(objs, 10) def get_or_create(self, defaults=None, **kwargs): # 若是存在,則獲取,不然,建立 # defaults 指定建立時,其餘字段的值 obj, created = models.UserInfo.objects.get_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 2}) def update_or_create(self, defaults=None, **kwargs): # 若是存在,則更新,不然,建立 # defaults 指定建立時或更新時的其餘字段 obj, created = models.UserInfo.objects.update_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 1}) def first(self): # 獲取第一個 def last(self): # 獲取最後一個 def in_bulk(self, id_list=None): # 根據主鍵ID進行查找 id_list = [11,21,31] models.DDD.objects.in_bulk(id_list) def delete(self): # 刪除 def update(self, **kwargs): # 更新 def exists(self): # 是否有結果
6.其餘
import pymysql from django.db import connection, connections connection.connect() conn = connection.connection cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("""SELECT * from app01_userinfo""") row = cursor.fetchone() connection.close()
# 數字自增 from django.db.models import F models.UserInfo.objects.update(num=F('num') + 1) # 字符串更新 from django.db.models.functions import Concat from django.db.models import Value models.UserInfo.objects.update(name=Concat('name', 'pwd')) models.UserInfo.objects.update(name=Concat('name', Value('666')))
# ########### 基礎函數 ########### # 1. Concat,用於作類型轉換 # v = models.UserInfo.objects.annotate(c=Cast('pwd', FloatField())) # 2. Coalesce,從前向後,查詢第一個不爲空的值 # v = models.UserInfo.objects.annotate(c=Coalesce('name', 'pwd')) # v = models.UserInfo.objects.annotate(c=Coalesce(Value('666'),'name', 'pwd')) # 3. Concat,拼接 # models.UserInfo.objects.update(name=Concat('name', 'pwd')) # models.UserInfo.objects.update(name=Concat('name', Value('666'))) # models.UserInfo.objects.update(name=Concat('name', Value('666'),Value('999'))) # 4.ConcatPair,拼接(僅兩個參數) # v = models.UserInfo.objects.annotate(c=ConcatPair('name', 'pwd')) # v = models.UserInfo.objects.annotate(c=ConcatPair('name', Value('666'))) # 5.Greatest,獲取比較大的值;least 獲取比較小的值; # v = models.UserInfo.objects.annotate(c=Greatest('id', 'pwd',output_field=FloatField())) # 6.Length,獲取長度 # v = models.UserInfo.objects.annotate(c=Length('name')) # 7. Lower,Upper,變大小寫 # v = models.UserInfo.objects.annotate(c=Lower('name')) # v = models.UserInfo.objects.annotate(c=Upper('name')) # 8. Now,獲取當前時間 # v = models.UserInfo.objects.annotate(c=Now()) # 9. substr,子序列 # v = models.UserInfo.objects.annotate(c=Substr('name',1,2)) # ########### 時間類函數 ########### # 1. 時間截取,不保留其餘:Extract, ExtractDay, ExtractHour, ExtractMinute, ExtractMonth,ExtractSecond, ExtractWeekDay, ExtractYear, # v = models.UserInfo.objects.annotate(c=functions.ExtractYear('ctime')) # v = models.UserInfo.objects.annotate(c=functions.ExtractMonth('ctime')) # v = models.UserInfo.objects.annotate(c=functions.ExtractDay('ctime')) # # v = models.UserInfo.objects.annotate(c=functions.Extract('ctime', 'year')) # v = models.UserInfo.objects.annotate(c=functions.Extract('ctime', 'month')) # v = models.UserInfo.objects.annotate(c=functions.Extract('ctime', 'year_month')) """ MICROSECOND SECOND MINUTE HOUR DAY WEEK MONTH QUARTER YEAR SECOND_MICROSECOND MINUTE_MICROSECOND MINUTE_SECOND HOUR_MICROSECOND HOUR_SECOND HOUR_MINUTE DAY_MICROSECOND DAY_SECOND DAY_MINUTE DAY_HOUR YEAR_MONTH """ # 2. 時間截圖,保留其餘:Trunc, TruncDate, TruncDay,TruncHour, TruncMinute, TruncMonth, TruncSecond, TruncYear # v = models.UserInfo.objects.annotate(c=functions.TruncHour('ctime')) # v = models.UserInfo.objects.annotate(c=functions.TruncDate('ctime')) # v = models.UserInfo.objects.annotate(c=functions.Trunc('ctime','year'))
from django.db.models.functions.base import Func class CustomeFunc(Func): function = 'DATE_FORMAT' template = '%(function)s(%(expressions)s,%(format)s)' def __init__(self, expression, **extra): expressions = [expression] super(CustomeFunc, self).__init__(*expressions, **extra) v = models.UserInfo.objects.annotate(c=CustomeFunc('ctime',format="'%%Y-%%m'"))
python執行命令
import subprocess v = subprocess.getoutput('ipconfig') print (v)
python Django初始化
1.建立工程 django-admin startproject 【工程名稱】 mysite - mysite # 對整個程序進行配置 - init - settings # 配置文件 - url # URL和函數對應關係,路由系統(函數稱爲視圖函數) - wsgi # 遵循WSIG規範,uwsgi + nginx,調用裏面的wsgiref的模塊,來實現socket,用來定義django使用什麼socket - manage.py # 管理Django程序: - python manage.py runserver 127.0.0.1:8080 - python manage.py startapp xx - python manage.py makemigrations - python manage.py migrate 2.建立app python manage.py startapp cmdb app: migrations 數據修改表結構(記錄修改表結構的) admin Django爲咱們提供的後臺管理 apps 配置當前app models ORM,寫指定的類 經過命令能夠建立數據庫結構 tests 單元測試 views 業務代碼(視圖函數) 3.ORM利用pymysql等第三方工具去連接,默認使用MySQLDB(修改Django默認連接mysql的方式) 1.建立數據庫 2.settings配置數據庫連接 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'site', 'USER': 'root', 'PASSWORD': '123456', 'HOST': '127.0.0.1', 'PORT': 3306, } } 3.更換mysqldb _init_.py(在建立的主程序的__init__.py裏面添加) import pymysql pymysql.install_as_MySQLdb() 4.在models裏面已經建立了一個類,這個類就是數據庫裏面的表 class UserInfo(models.Model): nid = models.AutoField(primary_key=True) #自增類型,而且設置主鍵(默認不寫這一行,django也會自動建立一個id的列,自增,而且爲主鍵) username = models.CharField(max_length=32) password = models.CharField(max_length=64) 建立外鍵 ug = models.ForeignKey('UserGroup',null=True,on_delete=models.CASCADE) 5.在settings裏面註冊 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cmdb', ] ==========================================================Django ORM操做========================================== 6.執行命令建立表 python manage.py makemigrations python manage.py migrate 報錯:SystemCheckError: System check identified some issues: # 解決方案: 因本身從新封裝user爲UserProfile故在 settings中 添加本身的 AUTH_USER_MODEL = "app_name.UserProfile" 7.建立外鍵 ug = models.ForeignKey('UserGroup',null=True,on_delete=models.CASCADE) 8.增刪改查 def index(request): #建立數據 #models.UserGroup.objects.create(title="管理員組") #建立數據 #models.UserInfo.objects.create(username="root",password="123",age="18",ug_id="1") #查找數據user_list是<QuerySet>類型的,也能夠看作是一個列表,QuerySet裏面是一個對象,每一個對象包含一條數據 user_list=models.UserInfo.objects.all() user_list=models.UserInfo.objects.filter(nid=1,username='root')#取一行 user_list=models.UserInfo.objects.filter(nid__gt=1)#取id大於1 user_list=models.UserInfo.objects.filter(nid__lt=1)#取id小於1 models.UserInfo.objects.filter(nid__lt=1).delete()#刪除 models.UserInfo.objects.filter(nid__lt=1).update(username="admin") #更新 for row in user_list: print(row.nid,row.age,row.username,row.password) print(user_list) return render(request,'index.html')
python Django 中間件
https://www.cnblogs.com/p0st/p/9793560.html
python Django Form和Ajax驗證
html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="f1" method="POST" action="/login/"> {% csrf_token %} <p> username:<input type="text" name="username">{{ obj.errors.username.0 }} </p> <p> password:<input type="password" name="password">{{ obj.errors.password.0 }} </p> <input type="submit" value="提交">{{ msg }} <a onclick="submitFrom();"></a> </form> <script src="/static/jquery-1.12.4.js"> function submitFrom(){ $.ajax({ url:'/ajax_login/', type:'POST', data:$('#f1').serialize(),{# 會在form裏面把全部的信息打包,包括csrf_token#} success:function(arg){ console.log(arg) } }) } </script> </body> </html>
後臺驗證
from django.shortcuts import render,redirect,HttpResponse from django.forms import Form from django.forms import fields # Create your views here. # def test(request): # print('123') # return HttpResponse('test') class loginForm(Form): # #不能爲空,長度6-18,郵箱格式 username = fields.CharField( max_length=18, min_length=6, required=True, error_messages={ 'required':'用戶名不能爲空', 'max_length':'長度不能大於18位', 'min_length':'長度不能小於6位', } ) # #不能爲空,長度6-18,郵箱格式 password = fields.CharField( min_length=6 ,required=True, error_messages={ 'required': '密碼不能爲空', 'max_length': '長度不能大於18位', 'min_length': '長度不能小於6位', } ) #from驗證 def login(request): if request.method =="GET": return render(request,'login.html') else: # user = request.POST.get('username') # #不能爲空,長度6-18,郵箱格式 # pwd = request.POST.get('password') # #不能爲空,長度爲6-18,必須包括字母數字下劃線 # if user == "root" and pwd == "123": # return redirect('http://www.baidu.com') # else: # msg = '帳號密碼錯誤' # return render(request,'login.html',{'msg':msg}) obj = loginForm(request.POST)#將用戶提交的數據傳給From去驗證 if obj.is_valid():#獲取校驗的信息,返回值爲True或False print(obj.cleaned_data) #字典類型,校驗成功以後,返回的正確的信息 return redirect("http://www.baidu.com") else: #若是用戶輸入格式正確,還要獲取錯誤信息的話,就會報錯 # print('username',obj.errors['username'][0]) #打印輸出errors的錯誤信息 # print('password',obj.errors['password'][0]) #obj.errors是一個對象那個,裏面有一個__str__:方法,轉化成字符串格式 return render(request,'login.html',{'obj':obj}) #在返回到html裏面的obj的調用 {{obj.errors.username.0}} #ajax提交驗證 def ajax_login(request): import json ret = {'status': True,'msg': None} obj = loginForm(request.POST) if obj.is_valid(): print(obj.cleaned_data) else: # print(obj.errors) # obj.errors對象 ret['status'] = False ret['msg'] = obj.errors v = json.dumps(ret) return HttpResponse(v)
python Django之Form組件
https://www.cnblogs.com/wupeiqi/articles/6144178.html
python 文件上傳
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Title</title> </head> <body> <form action="/f1/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="lalala"/> <input type="submit" value="提交"> </form> </body> </html>
import os def f1(request): if request.method =="GET": return render(request,'upload.html') else: file_obj=request.FILES.get('lalala') # print(file_obj.name) # print(file_obj.size) f =open(os.path.join('static',file_obj.name),'wb') # print(file_obj.chunks()) for chunk in file_obj.chunks(): f.write(chunk) f.close() return render(request, 'upload.html')
更多:https://www.cnblogs.com/wupeiqi/articles/5703697.html
python經常使用模塊
https://www.cnblogs.com/p0st/p/9874059.html
python生成驗證碼
Python生成隨機驗證碼,須要使用PIL模塊.
pip3 install pillow
基本使用
1.建立圖片 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在圖片查看器中打開 # img.show() # 保存在本地 with open('code.png','wb') as f: img.save(f,format='png') 2. 建立畫筆,用於在圖片上畫任意內容 img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') 3.畫點 img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') # 第一個參數:表示座標 # 第二個參數:表示顏色 draw.point([100, 100], fill="red") draw.point([300, 300], fill=(255, 255, 255)) 4.畫線 img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') # 第一個參數:表示起始座標和結束座標 # 第二個參數:表示顏色 draw.line((100,100,100,300), fill='red') draw.line((100,100,300,100), fill=(255, 255, 255)) 5.畫圓 img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') # 第一個參數:表示起始座標和結束座標(圓要畫在其中間) # 第二個參數:表示開始角度 # 第三個參數:表示結束角度 # 第四個參數:表示顏色 draw.arc((100,100,300,300),0,90,fill="red") 6.寫文本 img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') # 第一個參數:表示起始座標 # 第二個參數:表示寫入內容 # 第三個參數:表示顏色 draw.text([0,0],'python',"red") 7.特殊字體文字 img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') # 第一個參數:表示字體文件路徑 # 第二個參數:表示字體大小 font = ImageFont.truetype("kumo.ttf", 28) # 第一個參數:表示起始座標 # 第二個參數:表示寫入內容 # 第三個參數:表示顏色 # 第四個參數:表示顏色 draw.text([0, 0], 'python', "red", font=font)
驗證碼函數
函數 from PIL import Image,ImageDraw,ImageFont,ImageFilter import random def check_code(width=120, height=30, char_length=5, font_file='kumo.ttf', font_size=28): code = [] img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') def rndChar(): """ 生成隨機字母 :return: """ return chr(random.randint(65, 90)) def rndColor(): """ 生成隨機顏色 :return: """ return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255)) # 寫文字 font = ImageFont.truetype(font_file, font_size) for i in range(char_length): char = rndChar() code.append(char) h = random.randint(0, 4) draw.text([i * width / char_length, h], char, font=font, fill=rndColor()) # 寫干擾點 for i in range(40): draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor()) # 寫干擾圓圈 for i in range(40): draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor()) x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor()) # 畫干擾線 for i in range(5): x1 = random.randint(0, width) y1 = random.randint(0, height) x2 = random.randint(0, width) y2 = random.randint(0, height) draw.line((x1, y1, x2, y2), fill=rndColor()) img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) return img,''.join(code) 調用 img,code = rd_check_code() stream = BytesIO() img.save(stream, 'png') request.session['code'] = code return HttpResponse(stream.getvalue())
函數 from PIL import Image,ImageDraw,ImageFont,ImageFilter import random # 讀取硬盤中的文件在頁面顯示 # f= open ('static/imgs/1.png','rb') # data =f.read() # f.close() # return HttpResponse(data) def rd_check_code(): img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode='RGB') draw.point([60, 15], fill="red") draw.line((15, 10, 50, 30), fill='red') draw.line((45, 20, 100, 100), fill=(0, 0, 0)) draw.arc((0, 0, 30, 30), 0, 180, fill="red") #列表生成式 # v = ''.join([chr(random.randint(65,117)) for i in range(5)]) char_list= [] for i in range(5): char = chr(random.randint(65,90)) char_list.append(char) font = ImageFont.truetype("static/kumo.ttf", 28) draw.text([i*24, 0], char, (random.randint(0,255),random.randint(0,255),random.randint(0,255)), font=font) code = ''.join(char_list) return img,code 調用 img, code = rd_check_code() stream = BytesIO() img.save(stream, 'png') rquest.session['code'] = code return HttpResponse(stream.getvalue())
字體文件下載
python的類繼承
class BasePlugin(object): def __init__(self): pass def execute(self): self.linux() def linux(self): raise Exception('...........') # obj = BasePlugin() # obj.execute() class DiskPlugin(BasePlugin): def linux(self): return 'disk' obj = DiskPlugin() obj.execute() """ obj = DiskPlugin(),首先,類的實例化會先執行該類的__init__方法,若是沒有則會執行器父類的__init__ 要注意的是obj的對象是DiskPlugin,也能夠說是那個類加上括號,就是那個類的對象 obj.execute(),在執行的時候在本身的類裏面找到execute(),若是有執行,沒有的話向上找父類的execute(), self指的是DiskPlugin()的對象,self是誰,就從誰的類裏面找 """
??
python未明白的地方
fk自關聯
mangtomangto自關聯
cookie
session