Wyszukiwarka google w django
14 July 2008
Comments
Naszym celem będzie zrobienie prostej wyszukiwarki google w Django.- Pobieramy plik web_search.py.
- Tworzymy nowy projekt django o nazwie "google":
django-admin.py startproject google
- Tworzymy nową aplikacje o nazwie "searchengine":
python manage.py startapp searchengine
- Plik web_search.py umieszczamy w katalogu searchengine- Tworzymy w głównym katalogu projektu katalog templates
- Edytujemy settings.py i TEMPLATES_DIR ustawiamy na:
TEMPLATE_DIRS = (
'templates/'
)
python manage.py runserver 8080
Mamy przygotowane Django pod naszą wyszukiwarkę, tzn możemy zabrać się za widok i szablon. W katalogu templates/ tworzymy plik search.html o kodzie:
<form action="/" method="post">
<input type="text" name="term" size="30"> <input type="submit" value="Search">
</form>
- Edytujemy searchengine/views.py do postaci:
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
def search(request):
if request.POST:
print request.POST['term']
return HttpResponseRedirect("/")
else:
return render_to_response('search.html')
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'google.searchengine.views.search'),
)
web_search.py działa bardzo prosto, oto przykład:
from web_search import google
for (name, url, desc) in google('fraza', 20):
print name, url
Widok modyfikujemy do postaci:
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from google.searchengine.web_search import google
def search(request):
if request.POST:
return render_to_response('search.html', {'result': google(request.POST['term'], 10)})
#return HttpResponseRedirect("/")
else:
return render_to_response('search.html')
<form action="/" method="post">
<input type="text" name="term" size="30"> <input type="submit" value="Search">
</form><hr>
{% if result %}
{% for res in result %}
<li>{{ res }}</li>
{% endfor %}
{% endif %}
('Wine Development HQ', 'http://www.winehq.com/', 'Wine is a free implementation of Windows on Unix. WineHQ is a collection of resources for Wine developers and users.')
Element 0 - nazwa strony, element 1 - URL strony, element 2 - opis strony. A więc zmieniamy pętlę for na:
{% for res in result %}
<a href="{{ res.1 }}"><b>{{ res.0 }}</b></a><br />
{{ res.2 }}<br /><br />
{% endfor %}
RkBlog
Comment article