Commits

hideki nara committed 0f6c874

Gist を新規登録する簡単なサンプル

  • Participants
  • Parent commits 864f275

Comments (0)

Files changed (9)

File sample/app/github/fixtures/auth.json

+[
+  {
+    "pk": 19, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_logentry", 
+      "name": "Can add log entry", 
+      "content_type": 7
+    }
+  }, 
+  {
+    "pk": 20, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_logentry", 
+      "name": "Can change log entry", 
+      "content_type": 7
+    }
+  }, 
+  {
+    "pk": 21, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_logentry", 
+      "name": "Can delete log entry", 
+      "content_type": 7
+    }
+  }, 
+  {
+    "pk": 1, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_group", 
+      "name": "Can add group", 
+      "content_type": 2
+    }
+  }, 
+  {
+    "pk": 4, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_group", 
+      "name": "Can change group", 
+      "content_type": 2
+    }
+  }, 
+  {
+    "pk": 7, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_group", 
+      "name": "Can delete group", 
+      "content_type": 2
+    }
+  }, 
+  {
+    "pk": 2, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_permission", 
+      "name": "Can add permission", 
+      "content_type": 1
+    }
+  }, 
+  {
+    "pk": 5, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_permission", 
+      "name": "Can change permission", 
+      "content_type": 1
+    }
+  }, 
+  {
+    "pk": 8, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_permission", 
+      "name": "Can delete permission", 
+      "content_type": 1
+    }
+  }, 
+  {
+    "pk": 3, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_user", 
+      "name": "Can add user", 
+      "content_type": 3
+    }
+  }, 
+  {
+    "pk": 6, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_user", 
+      "name": "Can change user", 
+      "content_type": 3
+    }
+  }, 
+  {
+    "pk": 9, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_user", 
+      "name": "Can delete user", 
+      "content_type": 3
+    }
+  }, 
+  {
+    "pk": 10, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_contenttype", 
+      "name": "Can add content type", 
+      "content_type": 4
+    }
+  }, 
+  {
+    "pk": 11, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_contenttype", 
+      "name": "Can change content type", 
+      "content_type": 4
+    }
+  }, 
+  {
+    "pk": 12, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_contenttype", 
+      "name": "Can delete content type", 
+      "content_type": 4
+    }
+  }, 
+  {
+    "pk": 13, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_session", 
+      "name": "Can add session", 
+      "content_type": 5
+    }
+  }, 
+  {
+    "pk": 14, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_session", 
+      "name": "Can change session", 
+      "content_type": 5
+    }
+  }, 
+  {
+    "pk": 15, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_session", 
+      "name": "Can delete session", 
+      "content_type": 5
+    }
+  }, 
+  {
+    "pk": 16, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_site", 
+      "name": "Can add site", 
+      "content_type": 6
+    }
+  }, 
+  {
+    "pk": 17, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_site", 
+      "name": "Can change site", 
+      "content_type": 6
+    }
+  }, 
+  {
+    "pk": 18, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_site", 
+      "name": "Can delete site", 
+      "content_type": 6
+    }
+  }, 
+  {
+    "pk": 22, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_association", 
+      "name": "Can add association", 
+      "content_type": 10
+    }
+  }, 
+  {
+    "pk": 25, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_association", 
+      "name": "Can change association", 
+      "content_type": 10
+    }
+  }, 
+  {
+    "pk": 28, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_association", 
+      "name": "Can delete association", 
+      "content_type": 10
+    }
+  }, 
+  {
+    "pk": 23, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_nonce", 
+      "name": "Can add nonce", 
+      "content_type": 9
+    }
+  }, 
+  {
+    "pk": 26, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_nonce", 
+      "name": "Can change nonce", 
+      "content_type": 9
+    }
+  }, 
+  {
+    "pk": 29, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_nonce", 
+      "name": "Can delete nonce", 
+      "content_type": 9
+    }
+  }, 
+  {
+    "pk": 24, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "add_usersocialauth", 
+      "name": "Can add user social auth", 
+      "content_type": 8
+    }
+  }, 
+  {
+    "pk": 27, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "change_usersocialauth", 
+      "name": "Can change user social auth", 
+      "content_type": 8
+    }
+  }, 
+  {
+    "pk": 30, 
+    "model": "auth.permission", 
+    "fields": {
+      "codename": "delete_usersocialauth", 
+      "name": "Can delete user social auth", 
+      "content_type": 8
+    }
+  }, 
+  {
+    "pk": 1, 
+    "model": "auth.user", 
+    "fields": {
+      "username": "admin", 
+      "first_name": "hdknr", 
+      "last_name": "", 
+      "is_active": true, 
+      "is_superuser": true, 
+      "is_staff": true, 
+      "last_login": "2012-12-10T05:21:49.542Z", 
+      "groups": [], 
+      "user_permissions": [], 
+      "password": "pbkdf2_sha256$10000$GscHZAJAy0ER$fumj123kzLCug2X1sDGmpFKbYpvRFPy8PcA9nHYx0K4=", 
+      "email": "admin@admin.admin", 
+      "date_joined": "2012-12-03T06:15:10.703Z"
+    }
+  }, 
+  {
+    "pk": 3, 
+    "model": "auth.user", 
+    "fields": {
+      "username": "hdknra83b72298d9b4d8f", 
+      "first_name": "hdknr", 
+      "last_name": "", 
+      "is_active": true, 
+      "is_superuser": false, 
+      "is_staff": false, 
+      "last_login": "2012-12-10T05:21:10.019Z", 
+      "groups": [], 
+      "user_permissions": [], 
+      "password": "!", 
+      "email": "", 
+      "date_joined": "2012-12-04T00:04:56.914Z"
+    }
+  }
+]

File sample/app/github/fixtures/social_auth.json

+[
+  {
+    "pk": 1, 
+    "model": "social_auth.usersocialauth", 
+    "fields": {
+      "uid": "104647", 
+      "extra_data": "{\"access_token\": \"GITHUB_TEST_TOKEN\", \"expires\": null, \"id\": 104647}", 
+      "user": 3, 
+      "provider": "github"
+    }
+  }
+]

File sample/app/github/forms.py

+# -*- coding: utf-8 -*- from django import forms
+
+from django import forms
+from django.conf import settings
+from django.core.files import File
+from django.core.paginator import Paginator
+
+from models import *
+
+import os
+import uuid
+import re
+
+class GistItemForm(forms.ModelForm):
+
+    def __init__(self,*args,**kwargs):
+        super(GistItemForm,self).__init__(*args,**kwargs)
+
+    def save(self,*args,**kwargs):
+        try:
+            super(GistItemForm,self).save(*args,**kwargs )
+        except:
+            self.instance.save()
+
+    def to_preview(self):
+        ''' フォームのアイテムを全てhiddeに変更する 
+        '''
+        for k,f in self.fields.items():
+            if str(type(f)).find('Multi') >0: 
+                f.widget = forms.MultipleHiddenInput() 
+
+            elif isinstance(f.widget, forms.HiddenInput ) == False:
+                f.widget = forms.HiddenInput() 
+
+    class Meta:
+        model= Gist
+        exclude = ['gid','user',]
+        widgets = {
+            'usage': forms.RadioSelect(),
+        }
+
+class GistListForm(forms.Form):
+    pass
+

File sample/app/github/templates/github/gist/create.html

+{% extends "base.html" %}
+
+{% block style %}
+<style>
+div.form-row { clear:both; }
+div.form-col { float:left; }
+div.col-name { width:100px; }
+div.col-value{ width:100px; }
+</style>
+{% endblock %}
+
+{% block content %}
+
+<h1>Edit Gist</h1>
+{% if form %}
+<div id="form">
+<form method="post" /> {% csrf_token %}
+<div class="form-row">
+    <div class="form-col col-name"><label for="id_filename">ファイル名</label></div>
+    <div class="form-col cal-value">{{ form.filename }}</div>
+</div>
+<div class="form-row">
+    <div class="form-col col-name"><label for="id_contents">ファイル内容</label></div>
+    <div class="form-col col-value">{{ form.contents }}</div>
+</div>
+<div class="form-row">
+    <div class="form-col col-name">&nbsp;</div>
+    <div class="form-col col-value">
+    <input type="submit" name="action" value="save" />
+    </div>
+</div>
+<div class="form-row">
+    <div class="form-col col-name">&nbsp;</div>
+    <div class-"form-col col-value">
+    <span>1ファイルしか対応していません。。。</span>
+    </div>
+</div>
+</form>
+</div>
+{% endif %}
+
+{% endblock %}

File sample/app/github/templates/github/gist/edit.html

+{% extends "base.html" %}
+
+{% block content %}
+
+<h1>Edit Gist</h1>
+{% if form %}
+    {{ form }}
+    <input type="submit" name="action" value="save" />
+{% endif %}
+
+{% endblock %}

File sample/app/github/templates/github/gist/save.html

+{% extends "base.html" %}
+
+{% block content %}
+
+<h1>Git Created</h1>
+
+{% if gist_response %}
+    <a href="{{ gist_response.html_url }}">{{ gist_response.html_url }} </a>
+{% endif %}
+{% endblock %}

File sample/app/github/urls.py

 from views import *
 
 urlpatterns = patterns('',
+    url(r'social/logout', 'app.github.views.logout', name='app_github_logout'),
     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

 from django.http import HttpResponseRedirect
 from django.shortcuts import render_to_response
 from django.conf import settings
+from django.core.urlresolvers import reverse
+from django.contrib import auth
+
 
 from social_auth.decorators import dsa_view
 from django.utils.timezone import now
         },
         context_instance=template.RequestContext(request),)
 
+def logout(request):
+    ''' logout '''
+    auth.logout(request)
+    return  HttpResponseRedirect( reverse('app_github_default'))
+
 def pipeline_binding(*args,**kwargs):
     '''
     '''
 
 
 class GistView(FormView):
-    template_name = "github/gist/show.html"
-    form_class = GistForm
+    template_name = "github/gist/item.html"
+    form_class = GistItemForm
 
     def dispatch(self, request, *args, **kwargs):
         #:
+        if kwargs['command'] in [None,'list','']:
+            #:一覧
+            kwargs['command'] = 'list'
+            self.form_class = GistListForm
+        else:
+            kwargs['command'] = kwargs['command'].replace('/','')
+            
+        self.template_name = "github/gist/%(command)s.html" % 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(
                     ))
 
     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
+        vals =  self.get_form_kwargs()   #:GET,POST & FILES
+        vals['initial'] = {'user': self.request.user, }
+        if self.kwargs['command'] != None:
+            form_class = GistItemForm
+
         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))	
+#            log.debug(str(e))	
+            print str(e)
             raise e
 
         return form_class()          #:TODO: should be error?      
         ''' コンテキストデータ '''
         ret = super(GistView,self).get_context_data(**kwargs)
         #: 追加はここで
+        form = kwargs.get('form',None)
+        if form and form.instance and form.instance.response:
+            ret['gist_response'] = form.instance.response.json 
         return ret
     
     def form_valid(self, form):
         ''' ''' 
         try:
             action = self.request.POST.get('action',u'edit') 
+            form.instance.user = self.request.user
             { 
-                "save": lambda : form.save(session_key= self.request.session.session_key),
+                "save": lambda : form.save(),
                 "edit": lambda : True,
                 "preview": lambda : form.to_preview(),
             }[action](); 
+            
         except Exception,e:
             action = "edit"
-            log.debug(str(e))	
+            print str(e)
 
-        self.template_name = "recommends/item/%s.html" % action
+        self.template_name = "github/gist/%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)
 
-

File sample/app/templates/base.html

 <html lang="ja">
   <head>
     <meta charset="utf-8" />
+    {% block style %}{% endblock %}
   </head>
   <body>
     <div id="social">
         <div>
         {% if request.user.is_authenticated %}
-            {{ request.user }}
+            {{ request.user }} <a href="{% url app_github_gist gid='' command='create'  %}">New Gist</a> 
+            <a href="{% url app_github_logout %}">ログアウト</a>
+            
         {% else %}
             <a href="{% url socialauth_begin backend='github' %}">Github</a>
         {% endif %}