目前我已经设置了我的网站,并且有一个搜索栏和搜索按钮,我希望在我的api.py文件中执行我的api功能。 api.py文件如下所示:
import urllib2
import json
locu_api = '****'
def loc_search(request):
query = request.GET.get('query')
api_key = locu_api
url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key
locality = query.replace(' ', '%20')
final_url = url + "&locality=" + locality + "&category=restaurant"
json_obj = urllib2.urlopen(final_url)
data = json.load(json_obj)
for item in data['objects']:
print item['name']
print item['phone']
我已添加到我的urls.py中:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib import admin
urlpatterns = patterns(
"",
url(r"^$", TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r"^admin/", include(admin.site.urls)),
url(r"^account/", include("account.urls")),
url(r"^api/", 'loc_search', name="search"),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我在我的网址中是否正确?我的api文件和我的urls.py在我的主文件夹中?那就是说我已经在我的形式中称它为:
<form action="{% url "search" %}">
<div class="input-group">
<input id="address" type="textbox" placeholder="City or Zipcode" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="addressSearch">Search</button>
</span>
</div>
</form>
但是当我搜索没有任何反应时。据我所知,我相信我已经正确设置但我显然是错的,我对django来说相当新,所以任何帮助都会非常感激
答案 0 :(得分:1)
你的api电话第一个问题
我强烈建议你使用requests否则你会做像locality = query.replace(' ', '%20')
这样的urlencodes空格之类的内容,但是其他所有内容如öäü+ *?等?
import requests
api_params = {'api_key':locu_api, 'locality': locality, 'category':'restaurant'}
apicall = requests.get(api_url, params=api_params)
json_respons = apicall.json()
你的第二个问题是(Daniel Roseman提到它)这是一个视图(应该在views.py中)并且必须返回一个http响应。 docs
copypasta
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
# this will return a html as a http response
return HttpResponse(html)
在询问基础知识之前,您应该执行django tutorial