python+django(二)用戶登錄驗(yàn)證

7.模型激活和數(shù)據(jù)表創(chuàng)建,需要依次執(zhí)行以下命令

python38?manage.py?makemigrations app002

python38?manage.py?sqlmigrate app002 0001

python38?manage.py?migrate

這樣之后,poi_db_user(在setting中寫了)數(shù)據(jù)庫(kù)中就會(huì)多一個(gè)app002_user數(shù)據(jù)表,字段為model.py中設(shè)置的字段。

往里面添加數(shù)據(jù):

insert into app002_user (id,username,password,create_date) values (1,'lxx','666999','220405');

查看數(shù)據(jù)表里的內(nèi)容:

接下來(lái)實(shí)現(xiàn)最終目的,登錄驗(yàn)證然后下載文件。

參考了這兩個(gè)教程:https://www.jb51.net/article/165880.htm

https://blog.csdn.net/Lockey23/article/details/73196502

進(jìn)行了一些修改,最后成功啦,粘一下代碼吧。


(1)mysite001/settings.py

from pathlibimport Path

import os

import pymysql

INSTALLED_APPS= [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'app002'

]

pymysql.install_as_MySQLdb()

DATABASES= {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'poi_db_users',# 數(shù)據(jù)庫(kù)庫(kù)名(需提前創(chuàng)建好數(shù)據(jù)庫(kù))

? ? ? ? 'USER': 'root',# 用戶名

? ? ? ? 'PASSWORD': '666999',# 連接密碼

? ? ? ? 'HOST': 'localhost',# 主機(jī)

? ? ? ? 'PORT': '3306',# mysql端口

? ? }

}

(1)mysite001/urls.py

from django.contribimport admin

from django.urlsimport path,include,re_path

urlpatterns= [

re_path(r'^app002/',include('app002.urls')),# 增加對(duì)應(yīng)關(guān)系

? ? path('admin/', admin.site.urls),

]

(3)app-002/urls.py

from django.urlsimport re_path

from .import views

urlpatterns= [

re_path(r'^login/$', views.login,name='login'),

re_path(r'^index/$', views.index,name='index'),

re_path(r'^download/',views.file_down,name="download"),

]

(4)app-002/views.py

from django.shortcutsimport render,redirect

from .modelsimport User

from functoolsimport wraps

import os

from django.httpimport FileResponse

from django.utils.encoding import escape_uri_path

def login(request):? # 登陸頁(yè)面

? ? if request.method=="POST":

? ? ? ? username=request.POST.get('username')

password=request.POST.get('password')

user=User.objects.filter(username=username,password=password)

print(user)

if user:

? ? ? ? ? ? #登錄成功

# 1,生成特殊字符串

# 2,這個(gè)字符串當(dāng)成key,此key在數(shù)據(jù)庫(kù)的session表(在數(shù)據(jù)庫(kù)存中一個(gè)表名是session的表)中對(duì)應(yīng)一個(gè)value

# 3,在響應(yīng)中,用cookies保存這個(gè)key ,(即向?yàn)g覽器寫一個(gè)cookie,此cookies的值即是這個(gè)key特殊字符)

? ? ? ? ? ? request.session['is_login']='1' # 這個(gè)session是用于后面訪問(wèn)每個(gè)頁(yè)面(即調(diào)用每個(gè)視圖函數(shù)時(shí)要用到,即判斷是否已經(jīng)登錄,用此判斷)

# request.session['username']=username # 這個(gè)要存儲(chǔ)的session是用于后面,每個(gè)頁(yè)面上要顯示出來(lái),登錄狀態(tài)的用戶名用。

# 說(shuō)明:如果需要在頁(yè)面上顯示出來(lái)的用戶信息太多(有時(shí)還有積分,姓名,年齡等信息),所以我們可以只用session保存user_id

? ? ? ? ? ? request.session['user_id']=user[0].id

return redirect('/app002/index/')

else:

? ? ? ? ? ? render(request,'app002/login.html',{'error_msg': "用戶名或密碼輸入錯(cuò)誤,請(qǐng)?jiān)俅屋斎?})

return render(request,'app002/login.html')

def check_login(f):

? ? @wraps(f)

def inner(request,*arg,**kwargs):

? ? ? ? if request.session.get('is_login')=='1':

? ? ? ? ? ? return f(request,*arg,**kwargs)

else:

? ? ? ? ? ? return redirect('/app002/login/')

return inner

@check_login

def index(request):#登陸成功之后跳轉(zhuǎn)的頁(yè)面

? ? user_list= User.objects.all()

context= {'user_list': user_list}

return render(request,'app002/index.html', context)

def file_down(request):

? ? file_name= "要共享的數(shù)據(jù)集.rar"

? ? base_dir= os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# 項(xiàng)目根目錄

? ? file_path= os.path.join(base_dir,'upload', file_name)# 下載文件的絕對(duì)路徑

? ? if not os.path.isfile(file_path):? # 判斷下載文件是否存在

? ? ? ? return FileResponse("Sorry but Not Found the File")

def file_iterator(file_path,chunk_size=512):

? ? ? ? """

文件生成器,防止文件過(guò)大,導(dǎo)致內(nèi)存溢出

:param file_path: 文件絕對(duì)路徑

:param chunk_size: 塊大小

:return: 生成器

"""

? ? ? ? with open(file_path,mode='rb')as f:

? ? ? ? ? ? while True:

? ? ? ? ? ? ? ? c= f.read(chunk_size)

if c:

? ? ? ? ? ? ? ? ? ? yield c

else:

? ? ? ? ? ? ? ? ? ? break

? ? try:

? ? ? ? # 設(shè)置響應(yīng)頭

? ? ? ? response= FileResponse(file_iterator(file_path))

# 以流的形式下載文件,這樣可以實(shí)現(xiàn)任意格式的文件下載

? ? ? ? response['Content-Type']= 'application/octet-stream'#設(shè)置頭信息,告訴瀏覽器這是個(gè)文件

? ? ? ? response['Content-Disposition'] = 'attachment;filename="{}"'.format(escape_uri_path(file_name))

except:

? ? ? ? return FileResponse("Sorry but Not Found the File")

return response

(4)app-002/model.py

from django.dbimport models

# Create your models here.

class User(models.Model):

? ? id= models.IntegerField(primary_key=True)

username= models.CharField(max_length=16)

password= models.CharField(max_length=32)

create_date= models.DateTimeField('date published')

(6)templates/app002/login.html(后面設(shè)計(jì)界面時(shí)有改動(dòng),見下一個(gè)教程)

<body>

<h1>歡迎登錄!</h1>

<form action="/app002/login/" method="post">

? ? {% csrf_token %}

? ? <p>

? ? ? ? 用戶名:

? ? ? ? <input type="text" name="username">

? ? </p>

? ? <p>

? ? ? ? 密碼:

? ? ? ? <input type="text" name="password">

? ? </p>

? ? <p>

? ? ? ? <input type="submit" value="登錄">

? ? </p>

? ? <hr>

</form>

</body>

(7)templates/app002/index.html(后面設(shè)計(jì)界面時(shí)有改動(dòng),見下一個(gè)教程)

<body>

? ? <div class="col-md-4">

? ? <a href="{% url 'download' %}" rel="external nofollow" >

? ? ? ? 要下載的文件

? ? </a>

? ? </div>

</body>



之前的代碼

response['Content-Disposition']= 'attachment;filename="{}"'.format(file_name)

由于下載的文件是中文,所以下載的時(shí)候文件名總是“下載”也沒(méi)有后綴,按照下面代碼改了就好了:

from django.utils.encodingimport escape_uri_path

response['Content-Disposition']= 'attachment;filename="{}"'.format(escape_uri_path(file_name))

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容