簡介
用Django實現一個Web端垃圾分類的功能。
主要流程爲:在網頁上有一個搜索框,輸入搜索關鍵詞,獲取對應搜索數據。
這裏需要用到天行數據API接口,提供數據服務。網站爲:https://www.tianapi.com/,只需申請一個賬號可以免費使用接口數據(有次數限制,個人使用足夠)。
開發環境:Windows10,Pycharm,Python3.7,Django2.1
實現過程
相關配置
Django創建項目與app不多說,進入代碼編輯主要部分:
創建完項目和app後,_test項目目錄下還有一個_test文件夾,爲項目配置文件夾。
在配置文件夾中找到settigs.py文件,找到INSTALLED_APPS,將創建的app加入,代碼爲:
'testapp.apps.TestappConfig',
urls.py編輯
在配置文件夾中找到urls.py文件,將testapp的urls加入urlpatterns中,代碼爲:
path('', include('testapp.urls')),
記住需要導入include,代碼如下:
from django.urls import path, include
testapp中新建urls.py文件,代碼爲:
from django.urls import path
from . import views
app_name = 'testapp'
urlpatterns = [
# main
path('index/', views.index, name='index'),
path('get_search/', views.get_search, name='get_search'),
]
視圖編輯
編輯視圖函數views.py:
import json
import urllib.request
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'testapp/index.html', locals())
def get_search(request):
word = request.GET.get('q') # 獲取搜索表單關鍵詞,這裏的q與前端form表單中的字段值name的值一樣
key = '*****' # 天行數據賬號的key爲一串數字,記得替換
word_quote = urllib.request.quote(word) # 處理關鍵詞爲中文時的編碼問題
if word != '':
url = "http://api.tianapi.com/txapi/lajifenlei/index?key={}&word={}".format(key, word_quote)
try:
r = urllib.request.Request(url=url)
req = urllib.request.urlopen(r)
content = req.read().decode("utf-8") # 將獲取的內容編碼爲utf-8
json_response = json.loads(content) # 將數據轉化爲json格式,便於處理
except urllib.error.URLError as e:
pass
else:
# 判斷是否成功獲取數據
if json_response['code'] == 200 and (json_response['newslist'] is not None):
news_list = json_response["newslist"][:10] # 獲取前十條數據
elif json_response['code'] == 200 and (json_response['newslist'] is None):
empty_data = '未搜索到數據!請修改關鍵詞!'
else:
error = "暫時不能搜索,請稍後再試!"
return render(request, 'testapp/search.html', locals())
PS: 第一個視圖用來展示未搜索界面,第二個視圖用來展示搜索結果。
前端編輯
編輯前端html文件:
在testapp下新建templates文件夾,在templates下新建index.html和search.html文件。
index.html文件:
<p>HomePage</p>
<form class="" method="get" action="{% url 'testapp:get_search' %}">
<input type="search" class="" name="q" placeholder="Search" required>
<button type="submit" class="">搜索</button>
</form>
search.html文件如下:
<body>
<a href="{% url 'testapp:index' %}">Back home</a>
<form class="" method="get" action="{% url 'testapp:get_search' %}">
<input type="search" class="" name="q" placeholder="Search" required>
<button type="submit" class="">搜索</button>
</form>
<div>
{% if news_list %}
{% for item in news_list %}
<p>{{ item.name }}</p>
<p>{{ item.explain }}</p>
<p>{{ item.contain }}</p>
{% endfor %}
{% else %}
<p>{{ empty_data }}</p>
{% endif %}
</div>
</body>
PS:html文件未作優化處理,如CSS原生樣式或者bootstrap樣式。
瀏覽器搜索:http://127.0.0.1:8000/index/
主頁圖:
輸入關鍵詞,如:手機,搜索:
以上。