Я практикую Джанго, создавая веб-приложение, в котором я могу отправить электронное письмо одним словом, затем приложение переводит его (с английского на испанский или наоборот) и каждый день отправляет мне несколько слов для изучения.
Моя проблема: Я не знаю, куда поместить код веб-скрапера, который переводит поисковые термины, и я не знаю, как вызвать его при получении поискового запроса, чтобы результат можно было добавить кМодель результатов
Модели В настоящее время у меня есть две модели.Первая модель содержит мои условия поиска, а вторая модель содержит результаты перевода - оба наследуют от абстрактной модели с общими полями:
from django.db import models
from django.conf import settings
class CommonInfo(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Search(CommonInfo):
search_term = models.CharField(max_length=100)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True
)
def __str__(self):
return self.search_term
class Result(CommonInfo):
search = models.ForeignKey(
Search,
on_delete=models.SET_NULL,
null=True
)
translation = models.CharField(max_length=100)
example = models.TextField()
is_english = models.BooleanField(default=True)
def __str__(self):
return self.translation
Мое представление Мое представление имеет одну точку входакоторый получает запрос HTTP POST, содержащий проанализированный адрес электронной почты, от анализатора Sendgrid.Он извлекает слово для перевода (из строки темы), затем добавляет его в модель поиска, связывая его с соответствующим пользователем:
from vocab.models import Search
from django.views import View
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import re
from users.models import CustomUser
@method_decorator(csrf_exempt, name='dispatch')
class Parser(View):
def post(self, request, *args, **kwargs):
#pull out the from field
sender = request.POST.get('from')
#regex the actual email, turn into a string and assign to result_email
result_email = re.search("(?<=<).*?(?=>)", sender).group(0)
#lookup to see if it exists in the DB and throw an error if not
if CustomUser.objects.filter(email=result_email).exists() == False:
return HttpResponse("You do not have an account, please sign up first", status=401)
#PARSING
# parse subject
subject = str(request.POST.get('subject'))
# find user ID from DB
user = CustomUser.objects.get(email=result_email)
Search.objects.create(search_term=subject, user=user)
return HttpResponse("OK")
Веб-мастер Я создалконтур веб-скребка, который должен взять искомое слово, создать из него URL-адрес (на веб-сайт SpanishDict), затем использовать BeautifulSoup для перевода перевода и примеров предложений:
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
#creates a url from the word
def url_creator(word):
return 'https://www.spanishdict.com/translate/' + str(word).lower()
# get request using the url
def simple_get(url):
try:
with closing(get(url, stream=True)) as resp:
if is_good_response(resp):
return resp.content
else:
return None
except RequestException as error:
log_error('Error during request to %s : %s ' % (url, error))
return None
# checks the get request response is HTML
def is_good_response(resp):
content_type = resp.headers['Content-Type'].lower()
return (resp.status_code == 200
and content_type is not None
and content_type.find('html') > -1)
# logs an error if there are any issues
def log_error(error):
print(error)
# creates a beautiful soup object from the raw html
def bs_html_maker(raw_html):
return BeautifulSoup(raw_html, 'html.parser')
# finds the translation and example for the word being searched
def first_definition_finder(bs_html):
return bs_html.find(class_="dictionary-neodict-indent-1")
# works out the language being searched (inferring it from the results of the get request)
def language_finder(bs_html):
if bs_html.find(id="headword-and-quickdefs-es"):
return False
elif bs_html.find(id="headword-and-quickdefs-en"):
return True
else:
raise Exception("The word you searched didn't return anything, check your spelling")
# returns the translation, the example sentences and what language the search was in in a dictionary
def result_outputter(bs_html):
translation_dictionary = {}
is_english = language_finder(bs_html)
definition_block = first_definition_finder(bs_html)
definition = definition_block.find(class_="dictionary-neodict-translation-translation").string
examples = examples = definition_block.find(class_="dictionary-neodict-example").strings
example_string = "%s - %s" % (next(examples), next(examples))
translation_dictionary["definition"] = definition
translation_dictionary["example"] = example_string
translation_dictionary["is_english"] = is_english
return translation_dictionary
# pulls it all together in one method which will ideally be called whenever a search is saved to the database and the results can then be used to add the translation to the database
def vocab_translator(word):
url = url_creator(word)
raw_html = simple_get(url)
bs_html = bs_html_maker(raw_html)
return result_outputter(bs_html)
Myпроблема: Я не знаю, куда поместить код веб-мастера, который переводит поисковые термины, и я не знаю, как его вызвать при получении поискового запроса, чтобы результат можно было добавить в модель результатов
Любая помощь будет принята с благодарностью.Любые комментарии к моему коду также были бы полезны, так как я сейчас изучаю Django и нуждаюсь в каких-либо отзывах, которые вы можете дать.