Ejemplo n.º 1
0
    def handle(self, *args, **options):
        """Handle the command"""
        source_file = options['file']
        self.stdout.write(f'Checking if {source_file} exists...')

        try:
            # Open csv and loads info to db
            with open(source_file, 'r') as file:

                rows = list(csv.reader(file))
                count = 0

                for idx in range(1, len(rows)):
                    author = Author.objects.filter(name=rows[idx][0]).first()
                    if not author:
                        author = Author(name=rows[idx][0])
                        author.save()
                        count += 1

                self.stdout.write(self.style.SUCCESS(
                    f'Authors table populated with {count} authors!'
                    ))

        except FileNotFoundError:
            self.stdout.write(self.style.ERROR('File not found!'))
 def test_get_diff_with_callable_related_manager(self):
     resource = AuthorResource()
     author = Author(name="Some author")
     author.save()
     author2 = Author(name="Some author")
     self.book.author = author
     self.book.save()
     diff = resource.get_diff(author2, author)
     headers = resource.get_export_headers()
     self.assertEqual(diff[headers.index("books")], "<span>core.Book.None</span>")
Ejemplo n.º 3
0
 def test_get_diff_with_callable_related_manager(self):
     resource = AuthorResource()
     author = Author(name="Some author")
     author.save()
     author2 = Author(name="Some author")
     self.book.author = author
     self.book.save()
     diff = resource.get_diff(author2, author)
     headers = resource.get_export_headers()
     self.assertEqual(diff[headers.index('books')],
                      '<span>core.Book.None</span>')
Ejemplo n.º 4
0
    def save_status(self, data):
        """TODO"""
        status = Status.parse(self.api, json.loads(data))

        if not status.geo:
            # _datafile.write(data+'\n')
            return

        if Author.objects.filter(owner__userprofile__twitter_id=status.user.id_str).exists():
            # this tweet's author is on stargazer
            return

        try:
            author = Author.objects.filter(source=Author.T_TWITTER, external_id=status.user.id_str).get()
        except Author.DoesNotExist:
            author = Author(
                name=status.user.screen_name,
                avatar_uri=status.user.profile_image_url,
                source=Author.T_TWITTER,
                external_id=status.user.id_str,
            )
            author.save()

        try:
            post = Post.objects.filter(source=Post.T_TWITTER, external_id=status.id_str).get()
        except Post.DoesNotExist:
            lat = float(status.geo["coordinates"][0])
            lng = float(status.geo["coordinates"][1])

            try:
                addr = self._latlng2addr.get(lat, lng)
            except (LatLng2Addr.ConnectionFailed, LatLng2Addr.GeocodingFailed) as e:
                addr = ""

            # twitter api response in UTC
            created = status.created_at + timedelta(hours=8)

            post = Post(
                content=status.text,
                author=author,
                latitude=lat,
                longitude=lng,
                address=addr,
                source=Post.T_TWITTER,
                external_id=status.id_str,
                external_data=data,
                created=created,
            )
            post.save()

        return
Ejemplo n.º 5
0
def author_edit(request, author_id=None):
    msg = False
    if author_id:
        author = get_object_or_404(Author, pk=author_id)
        submit_url = reverse("dashboard:author_edit",
                             kwargs={'author_id':author.id})
    else:
        author = Author()
        submit_url = reverse("dashboard:author_add")

    if request.method == 'POST':
        form = forms.AuthorForm(request.POST, instance=author)
        if form.is_valid():
            print(form.cleaned_data)
            author_new = form.save(commit=False)
            author_new.owner = get_login_user(request.user.id)
            author_new.save()
            return redirect('dashboard:author_detail', author.id)
        else:
            print("validation fail")
    else:
        form = forms.AuthorForm(instance=author)
    return render(request,
                  'dashboard/author/edit.html',
                  {'msg': msg,
                   'form':form,
                   'author': author,
                   'submit_url': submit_url})
Ejemplo n.º 6
0
    def form_valid(self, form):
        post = form.instance

        if 0 == self.user.author_set.filter(source=Author.T_LOCAL).count():
            author = Author(name=self.user.username, source=Author.T_LOCAL,
                            owner=self.user)
            author.save()
        else:
            author = self.user.author_set.filter(source=Author.T_LOCAL).get()

        post.author = author

        self.success_url = '/post/recent/?'+\
            'addr=%(address)s&lat=%(latitude)s&lng=%(longitude)s'

        return super(CreateView, self).form_valid(form)
Ejemplo n.º 7
0
def new_login():
    form = BlogForm(request.form)
    if request.method == 'POST' and form.validate():
        blog = Routes.response_sql()
        title = form.title.data
        author = form.author.data
        email = form.email.data
        password = md5(form.password.data).hexdigest()

        blog.title = title
        blog.author = author
        blog.email = email
        blog.password = password
        blog.update_date = datetime.datetime.now()
        blog.genre = 'first blog'

        a = Author(author, email, password)
        db.session.add(a)

        db.session.commit()

    return redirect(url_for('admin.default'))

    response = Routes.session_blog()
    return render_template("admin/login.html", blog=response)
Ejemplo n.º 8
0
def author_edit(request, author_id=None):
    msg = False
    if author_id:
        author = get_object_or_404(Author, pk=author_id)
        submit_url = reverse("core:author_edit",
                             kwargs={"author_id": author.id})
    else:
        author = Author()
        submit_url = reverse("core:author_add")

    if request.method == "POST":
        form = forms.AuthorForm(request.POST, instance=author)
        if form.is_valid():
            print(form.cleaned_data)
            author_new = form.save(commit=False)
            author_new.owner = get_login_user(request.user.id)
            author_new.save()
            return redirect("core:author_detail", author.id)
        else:
            print("validation fail")
    else:
        form = forms.AuthorForm(instance=author)
    return render(
        request,
        "dashboard/author/edit.html",
        {
            "msg": msg,
            "form": form,
            "author": author,
            "submit_url": submit_url
        },
    )
Ejemplo n.º 9
0
    def add_authors_to(self, book):
        authors = []

        for form in self.forms:
            author_data = form.cleaned_data
            full_name = author_data.get('full_name', '')
            info = author_data.get('info', '')
            try:
                author = Author.objects.get(full_name=full_name)
                if info:
                    author.info = info
                    author.save()
            except ObjectDoesNotExist:
                author = Author(**author_data)
                author.save()
            authors.append(author)

        book.set_authors(authors)
Ejemplo n.º 10
0
def load_authors(file):     
    print '\nimporting authors'  
    for e in json.load(file):
        try:
            author = Author.objects.filter(name=e['name'], source=e['source']).get()
        except Author.DoesNotExist:
            author = Author(name=e['name'],
                            avatar_uri=e['avatar_uri'],
                            source=e['source'],
                            external_id=e['external_id'])
            
            if e['owner_name']:
                user = User.objects.filter(username=e['owner_name']).get()
                author.owner = user
            
            author.save()
            
        print '.',
        sys.stdout.flush() 
Ejemplo n.º 11
0
def copy_author_to_submission(user, book):
    author = Author(
        first_name=user.first_name,
        middle_name=user.profile.middle_name,
        last_name=user.last_name,
        salutation=user.profile.salutation,
        institution=user.profile.institution,
        department=user.profile.department,
        country=user.profile.country,
        author_email=user.email,
        biography=user.profile.biography,
        orcid=user.profile.orcid,
        twitter=user.profile.twitter,
        linkedin=user.profile.linkedin,
        facebook=user.profile.facebook,
    )

    author.save()
    book.author.add(author)

    return author
Ejemplo n.º 12
0
    def test_get_stats_type(self):
        """
        Tests if TypeError is raised
        """

        a_list = ["test", "type", "error"]
        self.assertRaises(TypeError, word_counter.get_stats, a_list)
        self.assertRaises(TypeError, word_counter.get_stats, None)
        correct_type = [
            Article(text="test",
                    author_id=Author(id="Test Test", name="testtest"))
        ]
        self.assertEqual(word_counter.get_stats(correct_type), {"test": 1})
Ejemplo n.º 13
0
    def form_valid(self, form):
        post = form.instance
        user = self.request.user
        
        try:
            author = user.author_set.filter(source=Author.T_LOCAL).get()
        except Author.DoesNotExist:
            author = Author(name=user.username, source=Author.T_LOCAL,
                            owner=user)
            author.save()

        post.author = author
        post.save()
        
        if self.request.POST['return']:
            success_url = self.request.POST['return'] + 'lat{}/lng{}/recent/'
                
        return HttpResponse(json.dumps({
                                'done': True,
                                'post_id': post.id,
                                'go_to': success_url.format(post.latitude, 
                                                            post.longitude)
                            }),
                            content_type='application/json')
Ejemplo n.º 14
0
def author_edit(request, author_id=None):
    msg = False
    if author_id:
        author = get_object_or_404(Author, pk=book_id)
        submit_url = reverse("dashboard:author_edit",
                             kwargs={'author_id': author.id})
    else:
        author = Author()
        submit_url = reverse("dashboard:author_add")

    if request.method == 'POST':
        form = forms.AuthorForm(request.POST, instance=author)
        if form.is_valid():
            author_new = form.save(commit=False)
            author_new.save()
            return redirect('dashboard:author_index')

    form = forms.AuthorForm(instance=author)
    return render(request, 'dashboard/author/edit.html', {
        'msg': msg,
        'form': form,
        'author': author,
        'submit_url': submit_url
    })
Ejemplo n.º 15
0
b.save()  # запись значения в базу данных

b.name = 'another first name'  # изменение атрибута
b.save()  # запись нового значения в базу
b.delete()  # удаление объекта из базы

# ** для присваивания связи между объектами:
# получение объекта класса entry через метод get, присаивание id объекта (pk-1)
entry = Entry.object.get()

# получение объекта класса blog
cheese_blog = Blog.object.get(name="Cheder Talk")
entry.blog = cheese_blog  # присваивание связи между entry и blog 1 к многим
entry.save()

genry = Author(name="Genry")  # создание автора
jonny = Author(name="Jonny")  # создание автора
entry.authors.add(genry, jonny)  # присваивание связи авторов к заметке & = &
# endregion -------------------------------------------------------------------

# region #* ОРМ базы данных ---------------------------------------------------
"""#** Для извлечения данных из базы (фильтр) нужно создать QuerySet - набор
объектов из базы. QuerySet соответствует SQL-выражению, а фильтры, которые к
нему применены, это условия в WHERE. QuerySet можно получить с помощью
менеджеров модели. Каждая модель имеет, по крайней мере, один менеджер, и по
умолчанию он называется objects."""
all_entries = Entry.objects.all()  # создание QuerySet всех объектов Entry
print(all_entries.query)  # .query - посмотреть соответствие SQL запроса

# создание QuerySet с фильтром по значению headline
entries = Entry.objects.filter(headline='name')