(python2.7)Django下实现查询图书馆藏地的web api

先贴代码,其它的以后再说
2016.9.23更新,更改了返回值数据类型,当请求带callback参数时返回jsonp,否则返回json

urls.py

from django.conf.urls import *
from view import getLocationByName

urlpatterns = [
    url(r'^libBook$', getLocationByName),
]

library.py

# -*- coding:utf-8 -*-
__author__='ssins'

from bs4 import BeautifulSoup
import urllib2
import urllib
import re

def getLocationByNo(no):
    try:
        url = 'http://202.119.252.200:8080/opac/item.php'
        values = {'marc_no': no}
        data = urllib.urlencode(values)
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
        requests = urllib2.Request(url, data, headers)
        respond = urllib2.urlopen(requests)
        bs = BeautifulSoup(respond.read(), 'lxml')
        tr = bs.find('tr', class_='whitetext')
        td = tr.find('td', width='25%')
        return td.string.strip()
    except:
        return None

def getNoByName(name):
    try:
        url = 'http://202.119.252.200:8080/opac/openlink.php'
        values = {'title': name}
        data = urllib.urlencode(values)
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
        requests = urllib2.Request(url, data, headers)
        respond = urllib2.urlopen(requests)
        bs = BeautifulSoup(respond.read(), 'lxml')
        h3 = bs.find('h3')
        a = h3.find('a')
        return re.search('\d+',a['href']).group()
    except:
        return None

view.py

# -*- coding:utf-8 -*-
__author__='ssins'

from django.http import HttpResponse
from library import getLocationByNo
from library import getNoByName
import json

def getLocationByName(requset):
    name = requset.GET['name']
    print type(name)
    location = getLocationByNo(getNoByName(name.encode('utf8')))
    result = {'location':location}
    resultJ = json.dumps(result)
    try:
        callback = requset.GET['callback']
        return HttpResponse(callback + '( ' + resultJ + ' );')
    except:
        return HttpResponse(resultJ)

你可能感兴趣的:((python2.7)Django下实现查询图书馆藏地的web api)