Commit cffc26d0d9e198edb51c359a04b3b40eb26a6df3

Fix PEP8 styles. Fix wrong info in README.

  - Fix PEP8 in most python files in classes.
  - Fix README saying '--recursive' in git clone.
README.md
(1 / 1)
  
8282
8383* Clone the repository from <https://git.pantoto.org/sweet-web/sweet-web-engine>
8484
85 > `` $ git clone --recursive https://git.pantoto.org/sweet-web/sweet-web-engine.git ``
85 > `` $ git clone https://git.pantoto.org/sweet-web/sweet-web-engine.git ``
8686
8787* It is recommended to do the installation inside a python virtual
8888 environment.
  
33
44# Script to run the application server in development mode
55
6import sys, os
6import sys
7import os
78
89# Get the path to the base directory of the app
910BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
  
33 __init__.py
44"""
55
6from flask import Flask, request, jsonify, render_template, make_response, g
76import os
87import logging
98from logging.handlers import RotatingFileHandler
109
10from flask import Flask, request, jsonify, render_template, make_response
11
1112from classes.database import db
1213from config import DefaultConfig
1314from classes import views
7171 db.app = app
7272 oauth.init_app(app)
7373
74
7475# return the current db instance
7576# TODO: is this needed so much?
7677def getDBInstance():
165165 log_handler = RotatingFileHandler(log_file, maxBytes=max_size,
166166 backupCount=10)
167167
168 if app.config.has_key('LOG_LEVEL'):
168 if 'LOG_LEVEL' in app.config:
169169 log_level = app.config['LOG_LEVEL'] or 'ERROR'
170170 else:
171171 log_level = 'ERROR'
  
22"""
33 __init__.py
44"""
5
56from database import db
67from oauth import oauth
78import models
  
33
44from sqlalchemy.exc import DontWrapMixin
55
6
67class AlreadyExistsError(Exception, DontWrapMixin):
78 pass
89
10
911class InvalidPayload(Exception, DontWrapMixin):
12 pass
13
14
15class ContextDoNotExist(Exception, DontWrapMixin):
1016 pass
  
3636 _redirect_uris = db.Column(db.Text)
3737 _default_scopes = db.Column(db.Text)
3838
39
4039 @property
4140 def client_id(self):
4241 return self.id
7272 def __str__(self):
7373 return '<Client: %s :: ID: %s>' % (self.name, self.id)
7474
75
7675 # create and persist the client to the database
7776 def persist(self):
7877 db.session.add(self)
153153#TODO: find out how to better structure the following code
154154
155155# OAuthLib decorators used by OAuthLib in the OAuth flow
156
157156@oauth.clientgetter
158157def loadClient(client_id):
159158 current_app.logger.debug('@oauth.clientgetter')
160159 #return Client.query.filter_by(id=client_id).first()
161160 return Client.query.get(client_id)
162161
162
163163@oauth.grantgetter
164164def loadGrant(client_id, code):
165165 current_app.logger.debug('@oauth.grantgetter')
166166 return Grant.query.filter_by(client_id=client_id, code=code).first()
167167
168
168169@oauth.grantsetter
169170def saveGrant(client_id, code, request, *args, **kwargs):
170171 current_app.logger.debug('@oauth.grantsetter')
171172 expires = datetime.utcnow() + timedelta(seconds=100)
172173 grant = Grant(
173 client_id = client_id,
174 code = code['code'],
175 redirect_uri = request.redirect_uri,
176 _scopes = ' '.join(request.scopes),
177 user = User.getCurrentUser(),
178 expires = expires
174 client_id=client_id,
175 code=code['code'],
176 redirect_uri=request.redirect_uri,
177 _scopes=' '.join(request.scopes),
178 user=User.getCurrentUser(),
179 expires=expires
179180 )
180181 db.session.add(grant)
181182 db.session.commit()
182183 return grant
183184
185
184186@oauth.tokengetter
185187def loadToken(access_token=None, refresh_token=None):
186188 current_app.logger.debug('@oauth.tokengetter')
191191 elif refresh_token:
192192 return Token.query.filter_by(refresh_token=refresh_token).first()
193193
194
194195@oauth.tokensetter
195196def saveToken(token, request, *args, **kwargs):
196197 current_app.logger.debug('@oauth.tokensetter')
206206 expires = datetime.utcnow() + timedelta(seconds=expires_in)
207207
208208 tok = Token(
209 access_token = token['access_token'],
210 refresh_token = token['refresh_token'],
211 token_type = token['token_type'],
212 _scopes = token['scope'],
213 expires = expires,
214 client_id = request.client.id,
215 user = request.user
209 access_token=token['access_token'],
210 refresh_token=token['refresh_token'],
211 token_type=token['token_type'],
212 _scopes=token['scope'],
213 expires=expires,
214 client_id=request.client.id,
215 user=request.user
216216 )
217217 db.session.add(tok)
218218 db.session.commit()
219219 return tok
220220
221
221222@oauth.usergetter
222223def getUser():
223224 return User.getCurrentUser()
224225
225226
226
227227# Authorized Clients
228228class AuthorizedClients(db.Model):
229229 """
258258
259259 @staticmethod
260260 def getByUser(user):
261 authorized_clients = [row.client for row in \
261 authorized_clients = [row.client for row in
262262 AuthorizedClients.query.filter_by(user_id=user.id).all()]
263263
264264 current_app.logger.debug('authorized clients %s', authorized_clients)
  
55from datetime import datetime
66import json
77
8from sqlalchemy.exc import IntegrityError
9
810from swtstore.classes import db
911from swtstore.classes.models.types import JSONType
1012from swtstore.classes.exceptions import AlreadyExistsError
  
88from swtstore.classes.database import db
99# custom SQLAlchemy type JSONType
1010from swtstore.classes.models.types import JSONType
11from swtstore.classes.utils import urlnorm # normalize URLs
11from swtstore.classes.utils import urlnorm # normalize URLs
1212from swtstore.classes.models import Context, User
13from swtstore.classes.exceptions import InvalidPayload, ContextDoNotExist
1314
15
1416class Sweet(db.Model):
1517 """ customary docstring """
1618
3232
3333 created = db.Column(db.DateTime, default=datetime.utcnow)
3434
35
3635 def __init__(self, who, what, where, how):
3736 current_app.logger.info('initing sweet..')
3837 self.who = who
3939 self.where = urlnorm(where)
4040 self.how = how
4141
42
4342 def __repr__(self):
4443 return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
4544 self.what, self.where)
5858
5959 return None
6060
61
6261 # create multiple sweets from a list of JSON
6362 @staticmethod
6463 def createSweets(who, payload):
6564 # the payload has to be a list; a list of swts
6665 for each in payload:
67 if 'what' not in each and 'where' not in\
68 each and 'how' not in each:
66 if 'what' not in each and 'where' not in each and 'how' not in\
67 each:
6968
70 raise InvalidPayload('Invalid payload %s \n for creating\
69 raise InvalidPayload('Invalid payload %s \n while creating\
7170 mutiple sweets' % (each))
7271 return None
7372
7777 what = Context.getByName(each['what'])
7878
7979 if what is None:
80 current_app.logger.info('Context "%s" do not exist. Aborting',
81 what)
82 g.error = 'Context do not exist'
83 abort(400) # this context doesn't exist!
80 raise ContextDoNotExist('Context %s do not exist!' %
81 (each['what']))
8482
8583 current_app.logger.debug('SWEET PAYLOAD\n---\n%s\n%s\n%s\n%s\n----',
86 who, what, each['where'], each['how'])
84 who, what, each['where'], each['how'])
8785
8886 new_sweet = Sweet(who, what, each['where'], each['how'])
8987
125125 #'created': self.created.isoformat()
126126 'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC'),
127127 }
128
129128
130129 # create and persist the sweet to the database
131130 def persist(self):
  
33# class:: Types
44# extend SQLAlchemy Types
55
6from datetime import datetime
76import json
87
98from sqlalchemy import types
9
1010
1111class JSONType(types.TypeDecorator):
1212 """
  
1from flask import Module, jsonify, request, make_response, abort, g, json,\
2 current_app
1from flask import Module, jsonify, request, make_response
2from flask import abort, g, json, current_app
33
4from swtstore.classes.models import Context
5from swtstore.classes.models import Sweet
6from swtstore.classes.exceptions import AlreadyExistsError, InvalidPayload
7from swtstore.classes.utils import urlnorm # normalize URLs
4from swtstore.classes.models import Context, Sweet
5from swtstore.classes.exceptions import AlreadyExistsError, InvalidPayload,\
6 ContextDoNotExist
7from swtstore.classes.utils import urlnorm # normalize URLs
88from swtstore.classes.utils.httputils import makeCORSHeaders
99from swtstore.classes import oauth
1010
6767 payload = request.json or request.data
6868 if not payload:
6969 current_app.logger.error('data not found in payload!')
70 g.error= 'data not found in payload!'
70 g.error = 'data not found in payload!'
7171 abort(400)
7272
7373 current_app.logger.debug('new sweet payload recvd.. %s', payload)
7878
7979 try:
8080 swts = Sweet.createSweets(who, payload)
81 except InvalidPayload(msg):
82 current_app.logger.error('Invalid Payload in request')
81 except (InvalidPayload, ContextDoNotExist) as e:
82 current_app.logger.error('Error creating sweets. Error: %s', e)
8383 abort(400)
8484
8585 response.status_code = 200
9999 response = makeCORSHeaders(response, origin)
100100
101101 if request.method == 'OPTIONS':
102 reponse.status_code = 200
102 response.status_code = 200
103103 return response
104104
105105 args = request.args
146146 current_app.logger.debug('getContextByName : %s', context)
147147 return jsonify(context.to_dict())
148148
149
149150# Get a specific context with its definition; based on id
150151@api.route('/contexts/<int:id>', methods=['GET'])
151152def getContextById(id):
194194 current_app.logger.debug('new context created: %s', new_context)
195195
196196 # all ok. save the new context
197 res = new_context.persist()
197 new_context.persist()
198198
199199 response.status_code = 200
200200 return response
  
11# -*- coding utf-8 -*-
22# classes/views/apps.py
33
4from flask import Module, jsonify, request, render_template, redirect,\
5 url_for, flash, abort
4from flask import Module, request, render_template, redirect,\
5 url_for, abort
66
7from hashlib import md5
87from werkzeug.security import gen_salt
98
109from swtstore.classes.models import Client, User
2929 abort(404)
3030
3131 new_app = Client(
32 id = gen_salt(40),
33 client_secret = gen_salt(50),
34 name = request.form.get('name'),
35 description = request.form.get('desc'),
36 user_id = current_user.id,
37 _host_url = request.form.get('host_url'),
38 _redirect_uris = urlnorm(request.form.get('redirect_uris')),
39 _default_scopes = ' '.join(request.form.get('scopes').split(',')),
40 _is_private = False
32 id=gen_salt(40),
33 client_secret=gen_salt(50),
34 name=request.form.get('name'),
35 description=request.form.get('desc'),
36 user_id=current_user.id,
37 _host_url=request.form.get('host_url'),
38 _redirect_uris=urlnorm(request.form.get('redirect_uris')),
39 _default_scopes=' '.join(request.form.get('scopes').split(',')),
40 _is_private=False
4141 )
4242 new_app.persist()
4343
  
11# -*- coding utf-8 -*-
22# classes/views/context.py
33
4from flask import Module, jsonify, request, render_template, redirect,\
5 url_for, json, current_app
4from flask import Module, request, render_template, redirect,\
5 url_for, json, current_app, abort
66
77from swtstore.classes.models import Context, User
88
99
1010context = Module(__name__)
1111
12
1213@context.route('/register', methods=['GET', 'POST'])
1314def register():
1415 current_user = User.getCurrentUser()
2020 return render_template('context/register.html')
2121
2222 if request.method == 'POST':
23 if not request.form.get('name') or not request.form.get('defn'):
24 abort(400)
23 if not request.form.get('name') or not request.form.get('defn'):
24 abort(400)
2525
2626 current_app.logger.debug('New Context: defn: %s ',
2727 request.form.get('defn'))
2929 current_app.logger.debug('Resulting json_ld %s', json_ld)
3030
3131 new_context = Context(
32 name = request.form.get('name'),
33 definition = json_ld,
34 user_id = current_user.id
32 name=request.form.get('name'),
33 definition=json_ld,
34 user_id=current_user.id
3535 )
3636 current_app.logger.debug('New Context created: %s', new_context)
3737 new_context.persist()
  
22# classes/views/frontend.py
33
44
5from flask import Module, jsonify, request, render_template, redirect,\
6 url_for, g, current_app
5from flask import Module, render_template
76
8from swtstore.classes.models import Sweet, User
7from swtstore.classes.models import Sweet
98
109
1110frontend = Module(__name__)
11
1212
1313@frontend.route('/', methods=['GET'])
1414def index():
  
11# -*- coding utf-8 -*-
22# classes/views/oauth.py
33
4from flask import Module, jsonify, request, render_template, redirect,\
5 url_for, current_app
6import requests
4from flask import Module, jsonify, request, render_template, current_app
75
86from swtstore.classes import oauth
97from swtstore.classes.models import Client, AuthorizedClients, User
3333 else:
3434 return render_template('oauth/authorize.html', **kwargs)
3535
36
3736 confirm = request.form.get('confirm', 'no')
3837 authorized = request.form.get('authorized', 'no')
3938 current_app.logger.debug('confirm authorize from user: %s', confirm)
5555 #print request.form
5656 current_app.logger.debug('access token touched..')
5757 return None
58
5859
5960@Oauth.route('/errors')
6061def error():
  
22# classes/views/sweet.py
33
44
5from flask import Module, jsonify, request, render_template, redirect,\
6 url_for, abort, json
5from flask import Module, render_template, abort
76
8from swtstore.classes.models import Context, Sweet, User
7from swtstore.classes.models import Sweet
98
109
1110sweet = Module(__name__)
11
1212
1313@sweet.route('/<int:id>', methods=['GET'])
1414def showSweet(id):
  
44import requests
55
66# flask imports
7from flask import Module, jsonify, request, render_template, session,\
8 make_response, url_for, redirect, json, current_app
7from flask import Module, request, render_template, session,\
8 make_response, url_for, redirect, json, current_app
99
1010# swtstore imports
1111from swtstore.classes.models import User, Sweet, Context, Client,\
12 AuthorizedClients
12 AuthorizedClients
1313
14from swtstore.classes.utils.httputils import makeCORSHeaders
1514from swtstore.config import DefaultConfig
1615
1716
1818
1919user = Module(__name__)
2020
21
2122@user.route('/login', methods=['POST'])
2223def login():
2324
6868 response.status_code = 500
6969 return response
7070
71
7172@user.route('/logout', methods=['POST'])
7273def logout():
7374
8282 response.status_code = 200
8383 return response
8484
85
8586@user.route('/me', methods=['GET', 'POST'])
8687def profile():
8788
138138 apps = Client.getClientsByCreator(user.id)
139139 return render_template('user/apps.html', apps=apps)
140140
141
141142@user.route('/me/authorized_apps', methods=['GET', 'POST'])
142143def authorizedApps():
143144
149149 if request.method == 'GET':
150150 authorized_clients = AuthorizedClients.getByUser(user)
151151 return render_template('user/authorized_apps.html',
152 authorized_clients=authorized_clients)
152 authorized_clients=authorized_clients)
153153
154154 # else POST request
155155 client_id = request.form.get('revoke-id', '')
  
11
2
23class DefaultConfig():
34
45 """
2121 # been done prior to editing this line.
2222 # Refer https://wiki.debian.org/PostgreSql#User_access for creating users
2323 # in postgresql.
24 SQLALCHEMY_DATABASE_URI =\
25 'dialect+driver://username:password@host:port/database'
24 SQLALCHEMY_DATABASE_URI = 'dialect+driver://username:password@host:port/database'
2625
2726 # Log level for the application
2827 LOG_LEVEL = 'ERROR'