時(shí)間:2023-07-11 14:24:01 | 來源:網(wǎng)站運(yùn)營
時(shí)間:2023-07-11 14:24:01 來源:網(wǎng)站運(yùn)營
實(shí)操篇:用Django實(shí)現(xiàn)Python建站:python利用Django搭建第一個(gè)網(wǎng)頁
cmd> pip install djangocmd> # windows安裝完成后,添加環(huán)境變量:cmd> # C:/Python37/Lib/site-packages/django/bin;cmd> # 如果是通過anaconda安裝,環(huán)境變量會(huì)自動(dòng)添加;cmd> # linux/mac可以不考慮環(huán)境變量的設(shè)置;
cmd> django-admin.py startproject project_namecmd> # 注意:在windows上如果啟動(dòng)錯(cuò)誤,嘗試用django-admin代替django-admin.py試試;cmd>cmd> django-admin startproject zwlcmd> # project_name為自定義,示例項(xiàng)目為zwl
2.2. 創(chuàng)建第一個(gè)APPcmd> cd zwlcmd> # 進(jìn)入項(xiàng)目文件夾,并創(chuàng)建第一個(gè)應(yīng)用zwl> django-admin startapp supconzwl> tree /fzwl> # 如果是在mac或者linux需要預(yù)裝tree,且中文目錄為tree -Nzwl> # linux下安裝tree的命令,sudo apt-get install tree
此時(shí),在工作目錄下的文件結(jié)構(gòu)如下圖所示zwl> # 此時(shí)一個(gè)django的項(xiàng)目就已經(jīng)搭建好了,查看是否成功zwl> python manage.py runserverzwl> # 在運(yùn)行時(shí)可以添加自定義端口,如python manage.py runserver 8008zwl> # 通過瀏覽器訪問127.0.0.1:8000,可以查看結(jié)果zwl> # 中斷快捷鍵:ctrl+c
瀏覽器訪問結(jié)果 cmd> python manage.py makemigrationsdjango.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.解決方案:D:/Program Files/Python/lib/site-packages/django/db/backends/mysql/base.py中的兩句注釋掉# if version < (1, 3, 13):# raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
cmd> python manage.py makemigrationsAttributeError: 'str' object has no attribute 'decode'解決方案:D:/Program Files/Python/lib/site-packages/django/db/backends/mysql/operations.py中的If判斷注釋掉# if query is not None:# query = query.decode(errors='replace')
cmd> net start mysqlcmd> # 如果mysql沒有啟動(dòng),則需要提前啟動(dòng)cmd> mysql -u root -pcmd> Enter password:mysql> show databases;
mysql> # 查看已有數(shù)據(jù)庫,可直接利用,如果沒有,則需要?jiǎng)?chuàng)建mysql> CREATE DATABASE supcon DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;mysql> # 建庫一定要改編碼為utf8!?。》駝t后續(xù)使用中文編碼可能會(huì)報(bào)錯(cuò);mysql> # 如果建庫時(shí)沒有設(shè)定編碼集,可以通過下面語句進(jìn)行更改mysql> show variables like '%char%';mysql> #查看字符集編碼mysql> alter database <數(shù)據(jù)庫名> character set utf8mb4;mysql> # 例:alter database db_user character set utf8mb4;mysql> alter table <表名> character set utf8mb4;mysql> # 例:alter table user character set utf8mb4;mysql> ALTER TABLE <表名> MODIFY COLUMN <字段名> <字段類型> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;mysql> # 例:ALTER TABLE comment MODIFY COLUMN content VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
3.2. 設(shè)置settings中的數(shù)據(jù)庫DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
zwl/settings.py修改為:DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2','mysql', 'sqlite3' or 'oracle' 'NAME': 'supcon', # Your db name, Or path to database file if using sqlite3 'USER': 'root', # Your db user name, Not used with sqlite3 'PASSWORD': '', # Your db password, Not used with sqlite3 'HOST': '127.0.0.1', # Your db host, set to empty string('') for default for localhost, Not used with sqlite3 'PORT': '3306' # Your db port, set to empty string('') for default, Not used with sqlite3 }}
在項(xiàng)目文件夾中找到init.py文件,初始化沒有內(nèi)容,需要添加下面兩句,調(diào)用pymysql包,使django和數(shù)據(jù)庫能夠進(jìn)行ORM操作。import pymysqlpymysql.install_as_MySQLdb()
在ORM框架中,它幫我們把類和數(shù)據(jù)表進(jìn)行了一個(gè)映射,可以讓我們通過類和類對象就能操作它所對應(yīng)的表格中的數(shù)據(jù)。用面向?qū)ο蟮姆绞饺ゲ僮鲾?shù)據(jù)庫的創(chuàng)建表、增加、修改、刪除、查詢等操作。把面向?qū)ο笾械念惡蛿?shù)據(jù)庫表一一對應(yīng),通過操作類和對象,對數(shù)據(jù)表實(shí)現(xiàn)數(shù)據(jù)操作,不需要寫sql,由orm框架生成。class BiPerson(models.Model): name = models.CharField(max_length=64, blank=True, null=True) person_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'bi_person'
編輯完成后,進(jìn)入終端/cmd窗口下執(zhí)行數(shù)據(jù)遷移,實(shí)現(xiàn)python類和mysql數(shù)據(jù)庫表之間的映射zwl> python manage.py makemigrationszwl> # 執(zhí)行數(shù)據(jù)遷移zwl> python magage.py migratezwl> # 同步表結(jié)構(gòu)
此時(shí),在mysql中會(huì)創(chuàng)建一張bi_person的表,可通過Navicat進(jìn)行查看# python console# 導(dǎo)入相關(guān)的模塊、工具from BIDashboard.models import BiPersonfrom django.core.serializers import serialize# 可查看表相關(guān)數(shù)據(jù),格式為querysetBiPerson.objects.all().values()Out[1]: <QuerySet [{'id': 1, 'name': '夏天', 'person_id': 1}, {'id': 2, 'name': '西索', 'person_id': 2}, {'id': 3, 'name': '蝸牛', 'person_id': 3}]># 如果需要進(jìn)行字段篩選,可以在values中取出對應(yīng)的字段BiPerson.objects.all().values('id','name')Out[2]: <QuerySet [{'id': 1, 'name': '夏天'}, {'id': 2, 'name': '西索'}, {'id': 3, 'name': '蝸牛'}]># 可通過serialize講queryset轉(zhuǎn)換成為json格式mapdata=BiPerson.objects.all()mapdata_json=serialize("json", mapdata,ensure_ascii=False)Out[3]: '[{"model": "BIDashboard.biperson", "pk": 1, "fields": {"name": "夏天", "person_id": 1}}, {"model": "BIDashboard.biperson", "pk": 2, "fields": {"name": "西索", "person_id": 2}}]'
另外一種獲取數(shù)據(jù)的方式是直接利用pymysql通過sql的方式進(jìn)行查詢# python consolefrom django.db import connectionsql='select * from bi_person'cur = connection.cursor()cur.execute(sql)cur.fetchall()Out[4]: ((1, '夏天', 1), (2, '西索', 2), (3, '蝸牛', 3)
zwl>mkdir templateszwl>tree /f # linux是tree -N
4.1. 編寫自己的第一個(gè)網(wǎng)頁<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>示例網(wǎng)站</title></head><body> <p>這是我的第一個(gè)網(wǎng)頁</p></body></html>
4.2. 建立視圖和html的映射from django.shortcuts import render# Create your views here.from django.http import HttpResponse,JsonResponsefrom supcon.models import BiPersondef test(request): return render(request,'first.html')
4.3. 配置網(wǎng)站路由from django.contrib import adminfrom django.conf.urls import urlfrom zwl import settingsfrom supcon import viewsurlpatterns = [ path('admin/', admin.site.urls), path('test/',views.test), ]
4.4. 查看網(wǎng)頁zwl> python manage.py runserverzwl> # 在運(yùn)行時(shí)可以添加自定義端口,如python manage.py runserver 8008zwl> # 通過瀏覽器訪問127.0.0.1:8000,可以查看結(jié)果zwl> # 中斷操作快捷鍵:ctrl+c
在瀏覽器中訪問:127.0.0.1:8000/test,即可查看頁面from django.shortcuts import render# Create your views here.from django.http import HttpResponse,JsonResponsefrom supcon.models import BiPersondef index(request): # 取出數(shù)據(jù)庫中的所有數(shù)據(jù) mydata=BiPerson.objects.all() # 需要傳遞給HTML5的對象 context={'data':mydata} return render(request,'first.html',context)
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>示例網(wǎng)站</title></head><body> <p>這是我的第一個(gè)網(wǎng)頁</p> <table> <thead> <tr> <th>person_id</th> <th>name</th> </tr> </thead> <tbody> {% for item in mydata %} <tr> <td>{{ item.person_id }}</td> <td>{{ item.name }}</td> </tr> {% endfor %} </tbody> </table></body></html>
zwl> python manage.py runserverzwl> # 在運(yùn)行時(shí)可以添加自定義端口,如python manage.py runserver 8008zwl> # 通過瀏覽器訪問127.0.0.1:8000,可以查看結(jié)果zwl> # 中斷操作快捷鍵:ctrl+c
此時(shí),一個(gè)基礎(chǔ)的網(wǎng)頁就已經(jīng)形成了,剩下的就是如何美化,以及服務(wù)部署
# ALLOWED_HOSTS = []ALLOWED_HOSTS ="*"
zwl> python manage.py runserver 0.0.0.0:8000zwl> # 通過瀏覽器訪問127.0.0.1:8000,可以查看結(jié)果zwl> # 中斷操作快捷鍵:ctrl+c
查看局域網(wǎng)ip地址,通過ipconfig,或者 - 在瀏覽器中訪問:172.21.10.40:8000/test,即可查看頁面zwl> python manage.py runserver 0.0.0.0:8000 &zwl> # 通過瀏覽器訪問127.0.0.1:8000,可以查看結(jié)果zwl> # 中斷操作快捷鍵:ctrl+c
關(guān)鍵詞:實(shí)現(xiàn)
客戶&案例
營銷資訊
關(guān)于我們
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。