Надеюсь, ты в порядке. Возможно, я допустил некоторые ошибки, но я бы хотел использовать API.
Итак, я решил создать новую папку под названием «рецепты». В этой папке я добавил папку «шаблоны» со страницами: рецепт. html и поиск. html
{% extends 'base.html' %}
{% block title %} Recipes searcher {% endblock %}
{% block body %}
<center>
<h2 style="padding-top: 3%;">
It's time for cooking! What do you have in the fridge? <br>
<small class="text-muted"> Let's warm up with a joke: {{ joke }} </small>
</h2>
<br><br>
<form action="/recipes">
<div class="input-group mb-3" style="max-width: 50%;">
<input type="text" class="form-control" placeholder="Apple, flour, sugar" aria-label="Ingridients" aria-describedby="button-addon2" name="ingridients">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit" id="button-addon2">Search</button>
</div>
</div>
</form>
</center>
{% endblock %}
и
{% extends 'base.html' %}
{% block title %} Recipes searcher {% endblock %}
{% block body %}
<h2 style="text-align: center"> <a href="/" style="text-decoration: none; color:red"> Recipes for you: </a></h2>
<div style="margin-left:35%;">
<ul class="list-unstyled">
{% for recipe in recipes %}
<li class="media">
<img src="{{recipe['image']}}" class="align-self-center mr-3" alt="..." width="15%" height="15%">
<div class="media-body">
<h5 class="mt-0 mb-1"><a href="/recipe?id={{ recipe['id'] }}">{{ recipe['title'] }}</a></h5>
{% if 'likes' not in recipe%}
How many minutes for preparation? {{recipe['preparationMinutes']}} <br>
How many minutes for cooking? {{recipe['cookingMinutes']}} <br>
How many likes has this recipe? {{recipe['aggregateLikes']}} <br>
{% else %}
How many your ingridients? {{recipe['usedIngredientCount']}} <br>
How many missed ingridients? {{recipe['missedIngredientCount']}} <br>
How many likes has this recipe? {{recipe['likes']}} <br>
{% endif %}
</div>
</li> <br>
{% endfor %}
</ul>
</div >
{% endblock %}
В settings / base.py в установленных приложениях я добавляю «recipes»
в recipes / views.py:
render_template, request
from wagtail.core.models import Page
from wagtail.recipes.models import GET
import requests
app = recipes(__name__)
url = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/"
headers = {
'x-rapidapi-host': "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com",
'x-rapidapi-key': "*********************************",
}
random_joke = "food/jokes/random"
find = "recipes/findByIngredients"
randomFind = "recipes/random"
@app.route('/')
def search_page():
joke_response = str(requests.request("GET", url + random_joke, headers=headers).json()['text'])
return render_template('search.html', joke=joke_response)
if __name__ == '__main__':
app.run()
@app.route('/recipes')
def get_recipes():
if (str(request.args['ingridients']).strip() != ""):
# If there is a list of ingridients -> list
querystring = {"number":"5","ranking":"1","ignorePantry":"false","ingredients":request.args['ingridients']}
response = requests.request("GET", url + find, headers=headers, params=querystring).json()
return render_template('recipes.html', recipes=response)
else:
# Random recipes
querystring = {"number":"5"}
response = requests.request("GET", url + randomFind, headers=headers, params=querystring).json()
print(response)
return render_template('recipes.html', recipes=response['recipes']
Теперь мне нужно создать новый шаблон, чтобы добраться до страницы рецептов. html с результатом. Но как это сделать я не очень знаю :)
Пробовал:
from recipes import views as recipes_views
url(r'^recipes/$', recipes_views.recipes, name='recipes'),
в
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
from search import views as search_views
from .api import api_router
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
url(r'^api/v2/', api_router.urls)
]
У меня ошибка:
Метод запроса: GET URL-адрес запроса: https://app.feedcool.fr/ Django Версия: 3.0.6 Тип исключения: SyntaxError Значение исключения:
неожиданный EOF во время синтаксического анализа (views.py, строка 41 ) Местоположение исключения: /home/dulo0814/monProjetWagtail/monsite/urls.py в строке 10 Python Исполняемый файл: /home/dulo0814/virtualenv/monProjetWagtail/3.7/bin/python3.7_bin Python Версия: 3.7. 3 Python Путь:
['/ home / dulo0814 / monProjetWagtail', '/ home / dulo0814 / monProjetWagtail', '/opt/passenger-5.3.7-5.el7.cloudlinux/src/helper-scripts' , '/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib64/python37.zip', '/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib64/python3.7', '/ home / dulo0814 / virtualenvag / montail /3.7/lib64/python3.7/lib-dynload ',' /opt/alt/python37/lib64/python3.7 ',' /opt/alt/python37/lib/python3.7 ', '/home/dulo0814/virtualenv/monProjetWagtail/3.7/lib/python3.7/site-packages '