如何在API中动态给用户输入?

时间:2018-09-10 12:12:05

标签: python django

我正在使用Django创建API。由于我要输入静态类型并以json格式获取输出。如何动态地提供用户输入。

views.py

from django.shortcuts import render,redirect
from django.views.generic import TemplateView 
from .models import *
from django.http import HttpResponse
from django.views.generic.edit import FormView
from .forms import TweetForm
from django.views import View
import json
import pdb
import tweepy
from pprint import pprint
import pickle

consumer_key = 'VR95CmIMrv7q7vfDoPcjC8NZS'
consumer_secret = 'YlWo6BzDnhXozSZnvnN1cIcjvRKrJFJVnYA9vvqMDocOdjyBNu'
access_key = '1006840281361047553-JQPFugH9xVNifKRY1b4BjgpdTLiVND'
access_secret =   '5R3DXQmf6Xf3FwZHZzqSU3P3oYQAReUqwux9ttj5Gj7K5'
def get_tweets(request):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)
    number_of_tweets=10
    tweets = api.user_timeline("realdonaldtrump") 
    tmp= []
    for tweet in tweets:
    tmp.append({"text":tweet.text,"user":tweet.user.name,"retweet_count":tweet.retweet_count,"img":tweet.user.profile_image_url})

    return HttpResponse(json.dumps(tmp))

urls.py

  from django.conf.urls import url
  from . import views

  urlpatterns = [
url(r'Tweet/$', views.get_tweets, name='Tweet'),

]

该输出正确,但是我们可以在tweets = api.user_timeline("realdonaldtrump") views.py输入中看到static行。如何动态提供它

1 个答案:

答案 0 :(得分:0)

def get_tweets(request, user):
    ...
    tweets = api.user_timeline(user) 
    ...
    return HttpResponse(json.dumps(tmp))

添加用户以查看功能时,您需要稍微更改网址

urlpatterns = [
    url(r'Tweet/(?P<user>[a-zA-Z0-9_\-]+)/$', views.get_tweets, name='Tweet'),
]

或者您可以将链接中的get键和值与request.GET.get('user')一起使用,并在不需要/Tweet/realdonaldtrump/的情况下将其传递给我,但是在这种情况下,它将是/Tweet/?user=realdonaldtrump,因此您可以选择选择您想要的。