项目源码下载:https://github.com/Cherish-sun/NEWS/tree/master
前端系统架构图

一、创建前端项目和应用
django-admin.py startproject newsapi
python manage.py startapp article
将static和templates文件夹拷贝到我们的项目中。
并在setting的APP里,添加article
INSTALLED_APPS = [
...
'artcile',
]
setting里添加 配置静态文件
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static').replace('', '/')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
web前端的工作原理是,请求后端对应的url,对url进行解析,传给html模板,返回给浏览器(用户)
1.基本方法-urlopen
urllib.request.urlopen(url,data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
- url: 需要打开的网址
- data:Post提交的数据
- timeout:设置网站的访问超时时间
直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型。
from urllib import request
response = request.urlopen(r’http://python.org/’) # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
page = response.read()
page = page.decode(‘utf-8’)
urlopen返回对象提供方法: - read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
- info():返回HTTPMessage对象,表示远程服务器返回的头信息
- getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
- geturl():返回请求的url
2.使用Request
urllib.request.Request(url,data=None, headers={}, method=None)
使用request()来包装请求,再通过urlopen()获取页面。
url = r’http://www.lagou.com/zhaopin/Python/?labelWords=label’
headers = {
‘User-Agent’: r’Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ’
r’Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3’,
‘Referer’: r’http://www.lagou.com/zhaopin/Python/?labelWords=label’,
‘Connection’: ‘keep-alive’ }
req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode(‘utf-8’)
用来包装头部的数据:
- User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言
- Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的
- Connection:表示连接状态,记录Session的状态。
二、views.py
1、导入包
from urllib import request, parse
try:
import json
except ImportError:
import simplejson as json
from django.shortcuts import render
from urllib.parse import urljoin
# Create your views here.
PAGESIZE = 5
2、引入所有API
category_url = 'http://127.0.0.1:8005/category/'
articles_url = 'http://127.0.0.1:8005/articleList/'
hotarticles_url = 'http://127.0.0.1:8005/hot_articleList/'
ad_url = 'http://127.0.0.1:8005/ad/'
items_url = 'http://127.0.0.1:8005/item/'
3、定义公用获取解析API方法
# 读取api数据
def getdata(url, data=None):
# url = r'http://xxx/xxx/xxxx?'
headers = {
'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
'Referer': r'',
'Connection': 'keep-alive',
'Content-Type':

本文介绍了使用Django进行前后端分离开发的新闻管理系统前端部分的创建过程,包括项目源码下载、前端系统架构图、创建前端项目和应用、以及views.py中的具体实现。前端工作原理涉及请求后端URL并解析,通过urlopen和Request方法处理HTTP请求,同时展示了如何在views.py中处理数据并渲染到模板。
最低0.47元/天 解锁文章
1836

被折叠的 条评论
为什么被折叠?



