1. hideki nara
  2. socialauth

Commits

hideki nara  committed 68534ee

Git モデルでsave()をしたらAPIコールするようにした

  • Participants
  • Parent commits c971deb
  • Branches master

Comments (0)

Files changed (5)

File sample/app/github/api.py

View file
     if sys_user == None:
         return None
 
-    ret = user.social_auth.filter( provider=provider )
+    ret = sys_user.social_auth.filter( provider=provider )
     return ret[0] if len(ret) > 0 else None
 
 def get_access_token(sys_user=None,social_id = None, social_user = None):
     METHOD="GET"
     params = {}
     def __init__(self,sys_user=None,social_id = None, social_user = None,access_token=None):
-        if social_user != None:
+        if social_user == None:
             social_user = get_social_user(sys_user,social_id ) 
 
         self.social_user = social_user
-        self.access_token = access_token or set_access_token(self.social_user )
+        self.access_token = access_token or get_access_token(social_user = self.social_user )
 
     def endpoint(self,path):
         ''' 指定したパスでエンドポイントを返す '''

File sample/app/github/models.py

View file
 from django.db import models
+from django.contrib.auth.models import User
 
-# Create your models here.
+from api import Gist as GistApi, get_social_user
+
+class Gist(models.Model):
+    user    = models.ForeignKey(User)
+    gid     = models.CharField(u'Gist ID',max_length=100,null=True,blank=True,default=None)
+    filename = models.CharField(u'File Name',max_length=100)
+    contents = models.TextField(u'Contents') 
+    response = None
+
+    def save(self,*args,**kwargs):
+        ''' '''
+        if self.gid == None:
+            ''' create '''
+            client = GistApi(social_user = self.social_auth )
+            client.add_file(self.filename,self.contents )
+            self.response = client.create()
+
+    @property
+    def social_auth(self):
+        return self.user and get_social_user(self.user) 
+
+    class Meta:
+        abstract=True

File sample/app/github/tests.py

View file
         res = gist.list()
         for g in res.json:          #: response is list
             print g['description'], g['public'],g['user']['login'],g['comments']   
+            print g
 
     def test_gist_create_simple(self):
 
         print res.request.url,res.request.headers
         print dir( res.request )
 #        print dir(res)
+
+class GistViewTest(TestCase):
+
+    fixtures=['auth.json','social_auth',] 
+    token = os.environ.get('GITHUB_TEST_TOKEN',None)
+
+    def setUp(self):
+        from django.contrib.auth.models import User
+        from social_auth.models import UserSocialAuth
+
+        self.assertEqual(UserSocialAuth.objects.count(),1)
+        usa=UserSocialAuth.objects.all()[0]
+        self.assertEqual( usa.extra_data['access_token'], 'GITHUB_TEST_TOKEN')
+
+        #: Update with Actual Token
+        usa.extra_data['access_token'] = self.token
+        usa.save()
+        
+        #: Check Updated Token
+        usa=UserSocialAuth.objects.all()[0]
+        self.assertEqual( usa.extra_data['access_token'], self.token)
+
+        self.test_user = usa.user
+
+    def test_gist_create_simple(self):
+        from app.github.models import Gist
+
+        g=Gist(user=self.test_user, filename="hoge.py", contents="xxxxxxxx" , ) 
+        self.assertEqual(g.social_auth.extra_data['access_token'],self.token )
+        g.save()
+        self.assertEqual(g.response.status_code,201)
+#        print g.response,g.response.json, type(g.response)

File sample/app/github/urls.py

View file
 # -*- coding: utf-8 -*-
 from django.conf.urls import patterns, include, url
+from views import *
 
 urlpatterns = patterns('',
     url(r'social/', include('social_auth.urls')),                           #: django-social-auth フレームワーク
+    url(r'gist/(?P<gid>\d*)(?P<command>.*)', GistView.as_view(), name="app_github_gist"),
     url(r'', 'app.github.views.default',name='app_github_default' ),
 )
 

File sample/app/github/views.py

View file
 from social_auth.decorators import dsa_view
 from django.utils.timezone import now
 from datetime import datetime
+
 from models import *
+from forms import *
 
 def default(request,*args,**kwargs):
     ''' default page '''
-    print args,kwargs
-    for i in  request.session.items():
-        print i
     return render_to_response( 'github/default.html',
         {  
         },
         context_instance=template.RequestContext(request),)
 
-
 def pipeline_binding(*args,**kwargs):
-    ''' アサーションに対するローカルアカウントのバインディングを決める
-
-        1. ログインしていない
-            - 新規ユーザーを作成
-            - ログインして既存のユーザーにバインド
-
-        2. ログインしている
-            - 新規ユーザーを作成
-            - 現在のユーザーにバインド
-            - ログオフして別のユーザーにログインしてバインド 
-    '''  
-    print "pipeline_binding"
+    '''
+    '''
     request = kwargs.get('request',None)
     assert request != None
 
             } , 
             context_instance=template.RequestContext(request),)
      
-#    request = kwargs.get('request',None)
-#    assert request != None
-#
-#    if request.method == "POST":
-#        bind = request.POST.get('bind',None)    #:new,current,other
-#    #: あるいは、GETでもログインユーザーがいて、そのユーザーにバインドする事を許可した場合
-#    else:
-#        return render_to_response( 'github/account/binding.html',
-#            { 
-#                'is_authenticated': request.user.is_authenticated(),
-#            } , 
-#            context_instance=template.RequestContext(request),)
 
+from django.views.generic.base import TemplateView
+from django.views.generic.edit import FormView
+
+
+class GistView(FormView):
+    template_name = "github/gist/show.html"
+    form_class = GistForm
+
+    def dispatch(self, request, *args, **kwargs):
+        #:
+        try:
+            #: call form_valid, form_invalid
+            res =  super(GistView,self).dispatch(request,*args,**kwargs)
+            #: force not redirect  
+            return res
+        except Exception,e:
+            return self.render_to_response(self.get_context_data(
+                        form=self.get_form(self.form_class)
+                    ))
+
+    def get_form_kwargs(self):  #:API
+        ''' API '''
+        res =  super(GistView,self).get_form_kwargs()
+        #: ここで強制的にデータを変換させたりとか 
+        return res
 
+    def get_form(self, form_class): 
+        ''' API: return するフォームは 'form' というコンテキストで参照できます。
+        '''
+        vals =  self.get_form_kwargs()   #:POST & FILES
+        try: 
+            if self.kwargs.get('id','None'):
+                vals['instance'] = form_class._meta.model.objects.get(id=self.kwargs['id'])
+            ret = form_class( ** vals )
+            return ret
+        except Exception,e:
+            log.debug(str(e))	
+            raise e
+
+        return form_class()          #:TODO: should be error?      
+
+    def get_context_data(self, **kwargs):
+        ''' コンテキストデータ '''
+        ret = super(GistView,self).get_context_data(**kwargs)
+        #: 追加はここで
+        return ret
     
+    def form_valid(self, form):
+        ''' ''' 
+        try:
+            action = self.request.POST.get('action',u'edit') 
+            { 
+                "save": lambda : form.save(session_key= self.request.session.session_key),
+                "edit": lambda : True,
+                "preview": lambda : form.to_preview(),
+            }[action](); 
+        except Exception,e:
+            action = "edit"
+            log.debug(str(e))	
+
+        self.template_name = "recommends/item/%s.html" % action
+                
+        return self.render_to_response(self.get_context_data(
+                        form = form
+                    ))
+        
+    def form_invalid(self, form):
+        return super(GistView ,self).form_invalid(form)
+
+