将数据从Google API导入到我的数据库

时间:2019-06-27 03:27:38

标签: python django

我需要创建从Google图书api导入数据并将其保存在模型中的视图。现在,我已经有了这种观点,但是我不知道如何在Django中做到这一点,我也不知道这是否好,下一步是什么。

def book_search(self, request):
    value = ''
    apikey = ''
    params = {'q': value, 'key': apikey}
    response = request.get('https://www.googleapis.com/books/v1/volumes', params=params)
    bookapi = response.json()

<<< strong>执行力>>

好吧,我尝试建立视图,但是现在我收到了错误消息:

AttributeError:'NoneType'对象没有属性'split'

当我尝试运行视图时。我收到我的表格,但是当我尝试对填写好的表格执行POST请求时,我收到了错误。

观看次数:

class GoogleBooks(View):
    model = Book
    form_class = SearchBookForm
    template_name = 'books/import_book.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})

    def search(self, value):
        googleapikey = ""
        params = {"q": value, 'key': googleapikey}
        google_books = self.request.get(url="https://www.googleapis.com/books/v1/volumes", params=params)
        book_dict = google_books.json()
        return book_dict

    def post(self, request, *args, **kwargs):
        form = self.form_class(self.request.POST)
        if form.is_valid():
            text = form.cleaned_data['key_word']
            bookshelf = self.search(text)
            booklist = 0
            for book in bookshelf:
                new_book = Book.objects.create(
                    title=book['items'][booklist]['volumeInfo']['title'],
                    published_date=book['items'][booklist]['volumeInfo']['publishedDate'][:3],
                    pages=book['items'][booklist]['volumeInfo']['pageCount'],
                    language=book['items'][booklist]['volumeInfo']['language'],
                )
                booklist += 1
                new_book.save()
            return redirect(reverse('books_index'))
        else:
            return redirect(reverse('add_book'))

表格:

class SearchBookForm(forms.Form):
    key_word = forms.CharField()

模板:

{% extends "books/base.html" %}
{% load bootstrap %}
{% block content %}
    <form method="GET">
            {{ form.as_p}}
            <button type="Submit" class="btn btn-primary">Search</button>
        </form>
{% endblock %}

这是我试图发现问题的方法,但是效果很好,而且我得到的正是我想要的:

import os
import requests
import json

class gbooks():
    googleapikey=""

    def search(self, value):
        params = {"q":value, 'key':self.googleapikey}
        r = requests.get(url="https://www.googleapis.com/books/v1/volumes", params=params)
        rj = r.json()
        j = rj['items'][1]['volumeInfo']['publishedDate'][:4]
        return print(j)



bk = gbooks()
bk.search("Harry Potter")

2 个答案:

答案 0 :(得分:1)

如果到目前为止,您获得的API response没有错误。然后,您可以遍历bookapi,并根据需要将每个对象值保存到Model中。

说明。

PS:在此示例中,我假设bookapi是可迭代的(如果您在使用api json响应时遇到任何问题,此链接https://docs.python.org/3/library/json.html会很有帮助)

        .....................
        .....................
        response = request.get('https://www.googleapis.com/books/v1/volumes', params=params)
        bookapi = response.json()
        # loop through your data and save to model
        for i in bookapi:
            new_entry = Model(
                         field_1 = i['obj_key1'],
                         field_1 = i['obj_key1']
                         )
            new_entry.save()

答案 1 :(得分:0)

好吧,经过漫长的战斗,我发现了问题并写了全功能的观点:

class GoogleBooks(View):
    form_class = SearchBookForm
    template_name = 'books/import_book.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})

    def search(self, value):
        googleapikey = ""
        params = {'q': value, 'key': googleapikey}
        google_books = requests.get(url="https://www.googleapis.com/books/v1/volumes", params=params)
        books_json = google_books.json()
        bookshelf = books_json['items']
        return bookshelf

    def add_book_to_library(self, bookshelf):
        for book in bookshelf:
            Book.objects.get_or_create(
                title=book['volumeInfo']['title'],
                published_date=book['volumeInfo']['publishedDate'][:4],
                pages=book['volumeInfo']['pageCount'],
                language=book['volumeInfo']['language'],
            )

    def post(self, request, *args, **kwargs):
        form = self.form_class(self.request.POST)
        if form.is_valid():
            keyword = form.cleaned_data['keyword']
            books = self.search(keyword)
            self.add_book_to_library(books)
            return HttpResponseRedirect(reverse_lazy('index_books'))

        return reverse_lazy('import_books')

这正是我想要的,问题是我试图从字典错误的值中退出。 我在此之前尝试过:

google_books = self.request.get(url="https://www.googleapis.com/books/v1/volumes", params=params)
        book_dict = google_books.json()
        return book_dict

booklist = 0
for book in bookshelf:
    new_book = Book.objects.create(
    title=book['items'][booklist]['volumeInfo']['title'],

但应这样:

google_books = requests.get(url="https://www.googleapis.com/books/v1/volumes", params=params)
        books_json = google_books.json()
        bookshelf = books_json['items']
        return bookshelf

for book in bookshelf:
            Book.objects.get_or_create(
                title=book['volumeInfo']['title'],