使用twython-django在用户提交表单时对其进行身份验证

时间:2013-01-03 18:29:40

标签: django oauth twitter twython

我正在构建一个Django应用程序,我正在尝试使用twython-django在提交表单时对Twitter用户进行身份验证。我试图按照这个例子https://github.com/ryanmcgrath/twython-django/tree/master/twython_django_oauth的建议编辑我的views.py,urls.py和models.py文件,但我只是在猜它,所以我确信这就是为什么它不起作用。

你能帮我解决一下如何让这个工作吗?我是Twitter包装的新手,所以任何帮助都会非常感激。

我正在努力实现的目标:

  1. 用户通过表单
  2. 提交邮件
  3. 要求用户在点击“提交”按钮
  4. 时验证他们的Twitter帐户
  5. 用户的消息,Twitter名称,Twitter screen_name,profile_image_url和followers_count保存在数据库中(我正在使用Heroku Postgres)
  6. 用户的个人资料图片,名称,屏幕名称和消息将打印到(类似Twitter)Feed中的index.html。
  7. 我的views.py:

     def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL):
         django_logout(request)
         return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
    
     def submit(request):
         twitter = Twython(
             twitter_token=settings.TWITTER_KEY,
             twitter_secret=settings.TWITTER_SECRET,
             callback_url=request.build_absolute_uri(reverse('alpha.views.submit'))
    )
    
    auth_props = twitter.get_authentication_tokens()
    
    request.session['request_token'] = auth_props
    return HttpResponseRedirect(auth_props['auth_url'])
    
    form = MessageForm(request.session.get('message'))
    if form.is_valid():
        new_message = form.save()
        return HttpResponseRedirect('/')
    else:
        request.session['message'] = request.POST
    
    twitter = Twython(
            twitter_token = settings.TWITTER_KEY,
            twitter_secret = settings.TWITTER_SECRET,
            oauth_token = request.session['request_token']['oauth_token'],
            oauth_token_secret = request.session['request_token']['oauth_token_secret'],
    )
    
    authorized_tokens = twitter.get_authentication_tokens()
    
    try:
        user = User.objects.get(username = authorized_tokens['screen_name'])
    except User.DoesNotExist:
            user = User.objects.create_user(authorized_tokens['screen_name'], authorized_tokens['oauth_token_secret'])
            profile = Message()
            profile.user = user
            profile.name = name
            profile.profile_image_url = profile_image_url
            profile.oauth_token = authorized_tokens['oauth_token']
            profile.oauth_secret = authorized_tokens['oauth_token_secret']
            profile.save()
    
    user = authenticate(
            username = authorized_tokens['screen_name'],
            password = authorized_tokens['oauth_token_secret']
    
    )
    login(request, user)
    return HttpResponseRedirect(redirect_url)
    

    免责声明:我是新手,所以上面的代码可能完全搞乱了!

1 个答案:

答案 0 :(得分:1)

是的,您的用例与twython-django的用例不同,但这并不意味着它不适用于您的情况,并且您可以使用库,因为它与您的流程一致。按照主页上的描述设置完所有内容之后,您需要为views.py:

添加类似内容
from django.shortcuts import redirect, reverse

def submit(request):
    # initial form submission, first check if we're authenticated
    # if we are, process as normal, otherwise redirect to the login
    # page. If you've set up twython-django correctly, it'll redirect
    # to twitter for the actual login.
    if request.method == "POST":
        if request.user.is_authenticated():
            form = MessageForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('/')
            else:
                # Modify this to display validation errors
                pass
        else:
            request.session['message'] = request.POST
            # the reverse(submit) resolves this view for redirection
            # back from the twitter authentication
            return redirect(settings.LOGIN_URL, next=reverse(submit))

    # A Get request, where we should first check for the message stored
    # We then process the form and remove it from session to prevent
    # accidental re-use.
    else:
        if 'message' in request.session and request.user.is_authenticated():
            form = MessageForm(request.session['message'])
            del request.session['message']
            if form.is_valid():
                form.save()
                return redirect('/')
            else:
                # Modify this to display validation errors
                pass
        else:
            # handle the case where this is a get request and the variable
            # isn't in session
            pass

至于加载他们的个人资料图片和关注者计数,twython django目前根本没有处理这些图片。你可以在github上分叉并将它们添加到TwitterProfile模型中,并将相应的代码添加到thanks视图中以加载它们,或者你可以在扩展TwitterProfile的代码中添加一个新模型。

from twython_django_oauth.models import TwitterProfile
from django import models

class ExtendedTwitterProfile(models.Model)
    profile = models.OneToOne(TwitterProfile, related_name="extended")
    avatar = models.CharField(max_length=255)
    followers = models.IntegerField()

并将代码添加到提交视图中,以根据需要添加/更新配置文件。

extended_profile = ExtendedTwitterProfile.objects.get_or_create(profile=request.user.twitterprofile)
extended_profile.avatar = avatarurl
extended_profile.followers = followercount

extended_profile.save()

您应该可以通过

访问这些详细信息
user.twitterprofile.extended.avatar

虽然,我过去曾使用网址来获取头像,例如:

# avatar redirection urls
url(r'^avatar/(?P<userid>[0-9A-Za-z_]+)$', redirect_to,
    { 'url' : 'http://api.twitter.com/1/users/profile_image/%(userid)s.json' }, name='avatar' ),    
url(r'^avatar/(?P<userid>[0-9A-Za-z_]+)/(?P<size>[a-z]+)$', redirect_to, 
    { 'url' : 'http://api.twitter.com/1/users/profile_image?screen_name=%(userid)s&size=%(size)s' } ),

在要显示头像的模板中,您只需使用url模板标签和img标签进行反向网址解析,如下所示:

<img src="{% url avatar userid=request.user.username %}" />

作为进一步的指针,您还可以通过Twitter的json API请求所有用户的基本详细信息

https://twitter.com/users/zandeez.json

例如,将以您可以在python中使用urllib甚至javascript / ajax的形式获取我的公开个人资料,具体取决于您想要对关注者计数做什么。

希望这应该让你排序,如果你需要更多的帮助可以随意询问。