Commit 4487bb80 authored by Vincent Le gallic's avatar Vincent Le gallic

Initialisation du Client HTTP Django.

Il gère déjà un embryon de login.
parents
# Django settings for Django_Client project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('20-100', 'legallic@crans.org'),
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'django_client', # Or path to database file if using sqlite3.
'USER': 'note', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Paris'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'fr-FR'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'yv72^i58*9mhz)=z7x9s^4(f&!m8_7a)$vz*hw6!@)_3ac+bdi'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'Django_Client.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'Django_Client.wsgi.application'
TEMPLATE_DIRS = (
"/home/vincent/note/new_note/Django_Client/templates"
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'note',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# ttl des cookies en secondes
SESSION_COOKIE_AGE=1000
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
import views
urlpatterns = patterns('',
url(r'^', include('note.urls')),
url(r'^/admin/', include(admin.site.urls)),
)
from django.http import HttpResponse
def rooturl(request):
return HttpResponse("c'est pas la bonne page")
"""
WSGI config for Django_Client project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django_Client.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
#from helloworld.wsgi import HelloWorldApplication
#application = HelloWorldApplication(application)
-----BEGIN CERTIFICATE-----
MIIEHzCCA4igAwIBAgIJAPuPFCLL9lQtMA0GCSqGSIb3DQEBBQUAMIG8MQswCQYD
VQQGEwJGUjEXMBUGA1UECBQOw45sZSBkZSBGcmFuY2UxDzANBgNVBAcTBkNhY2hh
bjEXMBUGA1UEChMOQkRFIEVOUyBDYWNoYW4xKzApBgNVBAsUIkF1dG9yaXTDqSBk
ZSBDZXJ0aWZpY2F0aW9uIE1hw650cmUxGjAYBgNVBAMTEUJERSBFTlMgQ2FjaGFu
IENBMSEwHwYJKoZIhvcNAQk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B7kjT5eJ65xL88ZS4yr8f3Vmg
4yus0TMRk/sLmdLDrXwBz0tmSYsCFqJbJqowAOyVn1UKZz0D4E2GFBN9/Fl0MVGf
lEEU
-----END CERTIFICATE-----
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAK3lNeaNyrt3FgSaHPLhZK+TL6RXnle2aeOVZvmoWuspZIdSgvDJM/ce
7CkSLZc+HL0DEXBiS1WYstiSMM6+LqUfSbDVVsbanFgqGIzFk4jz9HfMXh808nUI
rtNlZiguIIddnqmz8RikWh0oP51dctfXBhh9ZnXzgIzcqAHOC7k7AgMBAAE=
-----END RSA PUBLIC KEY-----
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django_Client.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
from note.models import Poll
from django.contrib import admin
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date']}),
]
admin.site.register(Poll, PollAdmin)
File added
from django.db import models
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(label="Pseudo")
password = forms.CharField(label="Mot de passe",widget=forms.PasswordInput(render_value=False))
droits = forms.ChoiceField(choices=[('all', 'Tous mes droits'), ('restricted','Moins de droits')])
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
File added
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
from django.conf.urls import patterns, include, url
urlpatterns = patterns('note.views',
url(r'^$', 'login_page'),
url(r'^index/$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
File added
# coding:utf8
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from note.models import Poll, LoginForm
import time
import random
import socket,ssl
import json
table="azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890()[]{}\\/=+-"
class NKError(Exception):
def __init__(self,msg):
Exception.__init__(self)
self.msg=msg
def __str__(self):
return str(self.msg)
def __unicode__(self):
return unicode(self.msg)
class NKRefused(NKError):
pass
class NKHelloFailed(NKError):
pass
class NKUnknownError(NKError):
pass
def connect_NK():
sock=socket.socket()
try:
# On établit la connexion sur port 4242
sock.connect(("127.0.0.1",4242))
# On passe en SSL
sock=ssl.wrap_socket(sock,ca_certs='../keys/ca_.crt')
# On fait un hello
sock.write('hello "HTTP Django"')
# On récupère la réponse du hello
out=sock.read()
out=json.loads(out)
except Exception as exc:
# Si on a foiré quelque part, c'est que le serveur est down
raise NKRefused(str(exc))
if out["retcode"]==0:
return sock
elif out["retcode"]==11:
raise NKHelloFailed(out["errmsg"])
else:
raise NKUnknownError(out["errmsg"])
def login_NK(username,password):
sock=connect_NK()
try:
sock.write('login [%s,%s,"bdd"]'%(json.dumps(username),json.dumps(password)) )
out=sock.read()
except Exception as exc:
# Si on a foiré quelque part, c'est que le serveur est down
raise NKRefused(str(exc))
return json.loads(out)
def login_page(request):
if request.method == 'POST': # If the form has been submitted...
form = LoginForm(request.POST) # A form bound to the POST data
if form.is_valid():
username=form.cleaned_data["username"]
password=form.cleaned_data["password"]
masque_droits=form.cleaned_data["droits"]
# On tente un login
try:
login_result=login_NK(username,password)
droits,retcode,errmsg=login_result["msg"],login_result["retcode"],login_result["errmsg"]
except NKRefused as exc:
erreurs=["Le Serveur NK2015 est down."]
return render_to_response('note/login.html',{'erreurs':erreurs})
except NKHelloFailed as exc:
erreurs=["La version du site utilisée n'est pas supportée par le serveur NK2015."]
return render_to_response('note/login.html',{'erreurs':erreurs})
except NKUnknownError as exc:
erreurs=["Une fucking <br> erreur inconnue s'est produite"]
erreurs+=str(exc).split("\n")
return render_to_response('note/login.html',{'erreurs':erreurs})
if retcode==0:
# login réussi
request.session["logged"]="ok"
return HttpResponseRedirect('/note/index')
else:
erreurs=['Login ou Mot de passe invalide']
form=LoginForm()
return render_to_response('note/login.html',{'form':form,'erreurs':erreurs},context_instance=RequestContext(request))
else:
erreurs=['Login ou Mot de passe invalide']
form=LoginForm()
return render_to_response('note/login.html',{'form':form,'erreurs':erreurs},context_instance=RequestContext(request))
else:
form = LoginForm() # An unbound form
if request.session.get("id",None)==None:
request.session["id"]="".join([table[random.randrange(len(table))] for i in range(15)])
request.session["date"]=time.strftime("%d/%m/%Y %T")
sess=str(dict(request.session))
return render_to_response('note/login.html',
{'sess':sess,
'date':request.session.get_expiry_age(),
'form':form
},context_instance=RequestContext(request))
def index(request):
if request.method == 'POST':
form = LoginForm(request.POST)
else:
username,password='not','POST'
test=False
l=[]
if test:
sock=socket.socket()
sock.connect(('127.0.0.1',4242))
sock=ssl.wrap_socket(sock,ca_certs='../keys/ca_.crt')
sock.write('hello "HTTP Django"')
sock.read()
sock.write('login ["%s","%s","bdd"]'%(username,password))
sock.read()
sock.write('quick_search [""]')
l=json.loads(sock.read())["msg"]
l=[str(i) for i in l]
sess=str(dict(request.session))
return render_to_response('note/index.html',
{'testl':l, 'sess':sess, 'date':request.session.get_expiry_age(),
},
context_instance=RequestContext(request))
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('note/detail.html',
{'poll': p,'sess' : str(dict(request.session)),
'date' : request.session.get_expiry_age()},
context_instance=RequestContext(request))
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
File added
404 not found
Oops !
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/polls/{{ poll.id }}/vote/" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
{% endfor %}
{{ sess }}</br>
Expire dans : {{ date }}s</br>
<input type="submit" value="Votez !" />
</form>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Note Kfet 2015 - Index</title>
</head>
<body>
This is a totally useless and uninteresting webpage.<br>
{{ sess }}<br>
dies in {{ date }}s<br>
{% for affiche in testl %}
<li>{{ affiche }}</li>
{% endfor %}
<a href="/note/index/">here !</a>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Note Kfet 2015</title>
</head>
<body>
<center><strong>Bienvenue sur la Note Kfet 2015</strong></center>
{{ sess }}<br>
dies in {{ date }}s<br>
{% if erreurs %}
{% for erreur in erreurs %}
<font color="#FF0000"><strong> {{ erreur }} </strong></font><strong><br>
{% endfor %}
{% endif %}
{% if form %}
<form action="/note" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Se connecter" />
{% endif %}
</form>
</body>
</html>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment