Djangos simple interface development

1. You need to configure the development environment before developing, get rid of Ubuntu. Django-admin startProject jiekou create the app python manage.py startApp myjiekou open the project and register the app in setting.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myjiekou',
)
Copy the code

5. Define the model class in the models.py file and define the required fields

# encoding=utf-8 from django.db import models # Create your models here. class MyModel(models.Model): # name = models.charfield (max_length=20) # age = models.charfield (max_length=100) # hobby = models.CharField(max_length=300)Copy the code

Manage. Py Makemigbar Python Manage. Py Migrate, Names, names, and Hoisting Python Manage. 8. Run Python manage.py runserver. By connecting to http://127.0.0.1:8000/admin see background management interface under 9, background management interface need to register before administrator account python manage. Py createsuperuser 10, why didn’t climb inside our new form it?


admin.png


from django.contrib import admin

from  myjiekou.models import MyModel
# Register your models here.

class MyAdmin(admin.ModelAdmin):
    list_display = ["name","age","hobby"]

admin.site.register(MyModel,MyAdmin)
Copy the code

Py runServer 12, Let’s look at the Admin interface again and add fields




admin1.png


How do we display admin data on the Django Web page? We need to access the django web page http://127.0.0.1:8000/index to display our output. First, we can simply display it

#encoding=utf-8 from django.shortcuts import render from django.http import HttpResponse # Create your views here. def Index (request): return HttpResponse(" Hello my PE teacher ")Copy the code


admin2.png

Again, we need to display SQLite data on our page, first importing our model classes

Setting. Py configuration TEMPLATES path = [{' BACKEND ':'. Django template. Backends. Django. DjangoTemplates', 'DIRS' : [os.path.join(BASE_DIR),'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]Copy the code
In the view.py file #encoding= utF-8 from Django. shortcuts Import render from Django. HTTP import HttpResponse from models import MyModel # Create your views here. def index(request): content = MyModel.objects.all() list = {"content":content} return render(request,"myjiekou/index.html",list)Copy the code
Index.html according to <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for item in content %} <li>{{ item.name }}</li> <li>{{ item.age }}</li> <li>{{ item.hobby }}</li> {% endfor %} </ul> </body> </html>Copy the code

Note: there will be some problems during the operation, such as the following, we will solve it

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

Copy the code

14. Chinese management interface

LANGUAGE_CODE = 'en-us'
Copy the code

15. Next, django interface development

First import the module from Django. HTTP import JsonResponseCopy the code
From myjiekou import views urlpatterns = [URL (r'^admin/', include(admin.site.urls))), url(r'^index/', views.index), url(r'^api/', views.api), ]Copy the code
Def API (request): list = [] item = {} content = mymodel.objects.all () for one in content: item["name"] = one.name item["age"] = one.age item["hobby"] = one.hobby list.append(item) return JsonResponse({"status":200,"date":list})Copy the code


admin3.png


Next I run the OC program to call the interface and see if it succeeds

Crawler crawls a web site

1. Re module: mainly uses regular matching to analyze captured data. 2. XPath: searches HTML nodes or elements for data filtering. JSON and JsonPATH: JSON data parsing The following example uses XPath to find HTML node or element parsing

# -*- coding:utf-8 -*- import urllib2,os import lxml.etree class Xunmall(): def __init__(self): Self. url = "http://www.xunmall.com" def get_html(self,p1 = ""): # headers = {# "user-agent ": "Mozilla/5.0 (Linux); The Android 6.0. Nexus 5 Build/MRA58N) AppleWebKit } Request = urllib2. request (self.url + p1) Response = urllib2.urlopen(request) html = response.read() return html def get_xpath(self): xmlcontent = lxml.etree.HTML(self.get_html()) xmllist = xmlcontent.xpath('//h2[@class="floor_name"]/text()') for item in  xmllist: with open('title.txt','a') as file: file.write(item.encode('utf-8') + '\n') file.close def get_image(self): xmlimage = lxml.etree.HTML(self.get_html()) imagelist = xmlimage.xpath('//div[@class="color_top"]/img/@src') if os.path.isdir('./imgs'): pass else: os.mkdir("./imgs") for item in imagelist: print self.url + item with open('imgs/' + (self.url + item)[-8:],'a+') as file: file.write(self.get_html(item)) file.close def get_theme(self): xmltheme = lxml.etree.HTML(self.get_html()) themelist = xmltheme.xpath('//h3[@class="floor_theme"]/text()') for item in themelist: with open('theme.txt','a') as file: file.write(item.encode('utf-8') + '\n') file.close sloganlist = xmltheme.xpath('//p[@class="slogan"]/text()') for item in sloganlist: with open('theme.txt','a') as file: file.write(item.encode('utf-8') + '\n') file.close give_outlist = xmltheme.xpath('//p[@class="give_out"]/text()') for item in give_outlist: with open('theme.txt', 'a') as file: file.write(item.encode('utf-8') + '\n') file.close def get_html1(self,p2): Request = urllib2.request (p2) response = urllib2.urlopen(request) HTML = response.read() return HTML # food def foodImageTitle(self): foodImage = lxml.etree.HTML(self.get_html()) foodImageList = foodImage.xpath('//div[@class="pro_image"]/img/@src') if os.path.isdir('./foodimage'): pass else: os.mkdir("./foodimage") for item in foodImageList: print item with open('foodimage/' + item[-20:],'a+') as file: Write (self.get_html1(item)) file.close # def detail(self): detailLink = lxml.etree.HTML(self.get_html()) detailLinkList = detailLink.xpath('//div[@class="nth_floor first_floor"]/div[@class="goods_box"]/ul[@class="item_list"]//a/@href') for item in detailLinkList: # print item[-18:] detailUrl = lxml.etree.HTML(self.get_html("/" + item[-18:])) detailImageList = detailUrl.xpath( '//div[@class="info-panel panel1"]/img/@src') for detailitem in detailImageList: If os.path.isdir('./' + item[-18:-5]): pass else: if os.path.isdir('./' + item[-18:-5]): pass else: os.mkdir("./" + item[-18:-5]) with open(item[-18:-5] + '/' + detailitem[-9:], 'a+') as file: Write (self.get_html1(detailitem)) file.close # Commodity title detailtitleList = detailurl.xpath ('//div[@class=" col-lG-7 item-inner"]//h1[@class="fl"]/text()') for title in detailtitleList: with open('foodtitle.txt', 'a+') as file: File. Write (title.encode(' UTF-8 ') + '\n') file. Close # goodnumberList = detailurl.xpath (' //div[@class=" col-lG-7 item-inner"]//li[@class="col-lg-5 col-md-5"]/text()') for number in goodnumberList: print number if os.path.isdir('./qrcoder'): pass else: os.mkdir("./qrcoder") with open('qrcoder', 'a+') as file: File. Write (number.encode(' utF-8 ') + '\n') file detailUrl.xpath('//div[@class="clearfixed"]//div[@class="barcode fr"]/img/@data_code') for item in coderImageList: print item with open('goodnumber.txt', 'a+') as file: file.write(item + '\n') file.close if __name__ == "__main__": # xunmall = xunmall () # xunmall.get_xpath() # xunmall. Get_image () # xunmall. Get_theme () # xunmall # xunmall.foodimagetitle () xunmall.detail()Copy the code

I will share Swift later. I will simply share the learning results and discuss and learn with the project team.