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.
  • Diff rendering mode:
  • inline
  • side by side

README.md

8282
83* Clone the repository from <https://git.pantoto.org/sweet-web/sweet-web-engine>83* 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
87* It is recommended to do the installation inside a python virtual87* It is recommended to do the installation inside a python virtual
88 environment.88 environment.

runserver.py

33
4# Script to run the application server in development mode4# Script to run the application server in development mode
55
6import sys, os
6import sys
7import os
78
8# Get the path to the base directory of the app9# Get the path to the base directory of the app
9BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))10BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))

swtstore/application.py

3 __init__.py3 __init__.py
4"""4"""
55
6from flask import Flask, request, jsonify, render_template, make_response, g
7import os6import os
8import logging7import logging
9from logging.handlers import RotatingFileHandler8from logging.handlers import RotatingFileHandler
109
10from flask import Flask, request, jsonify, render_template, make_response
11
11from classes.database import db12from classes.database import db
12from config import DefaultConfig13from config import DefaultConfig
13from classes import views14from classes import views
71 db.app = app71 db.app = app
72 oauth.init_app(app)72 oauth.init_app(app)
7373
74
74# return the current db instance75# return the current db instance
75# TODO: is this needed so much?76# TODO: is this needed so much?
76def getDBInstance():77def getDBInstance():
165 log_handler = RotatingFileHandler(log_file, maxBytes=max_size,165 log_handler = RotatingFileHandler(log_file, maxBytes=max_size,
166 backupCount=10)166 backupCount=10)
167167
168 if app.config.has_key('LOG_LEVEL'):
168 if 'LOG_LEVEL' in app.config:
169 log_level = app.config['LOG_LEVEL'] or 'ERROR'169 log_level = app.config['LOG_LEVEL'] or 'ERROR'
170 else:170 else:
171 log_level = 'ERROR'171 log_level = 'ERROR'

swtstore/classes/__init__.py

2"""2"""
3 __init__.py3 __init__.py
4"""4"""
5
5from database import db6from database import db
6from oauth import oauth7from oauth import oauth
7import models8import models

swtstore/classes/exceptions.py

33
4from sqlalchemy.exc import DontWrapMixin4from sqlalchemy.exc import DontWrapMixin
55
6
6class AlreadyExistsError(Exception, DontWrapMixin):7class AlreadyExistsError(Exception, DontWrapMixin):
7 pass8 pass
89
10
9class InvalidPayload(Exception, DontWrapMixin):11class InvalidPayload(Exception, DontWrapMixin):
12 pass
13
14
15class ContextDoNotExist(Exception, DontWrapMixin):
10 pass16 pass

swtstore/classes/models/client.py

36 _redirect_uris = db.Column(db.Text)36 _redirect_uris = db.Column(db.Text)
37 _default_scopes = db.Column(db.Text)37 _default_scopes = db.Column(db.Text)
3838
39
40 @property39 @property
41 def client_id(self):40 def client_id(self):
42 return self.id41 return self.id
72 def __str__(self):72 def __str__(self):
73 return '<Client: %s :: ID: %s>' % (self.name, self.id)73 return '<Client: %s :: ID: %s>' % (self.name, self.id)
7474
75
76 # create and persist the client to the database75 # create and persist the client to the database
77 def persist(self):76 def persist(self):
78 db.session.add(self)77 db.session.add(self)
153#TODO: find out how to better structure the following code153#TODO: find out how to better structure the following code
154154
155# OAuthLib decorators used by OAuthLib in the OAuth flow155# OAuthLib decorators used by OAuthLib in the OAuth flow
156
157@oauth.clientgetter156@oauth.clientgetter
158def loadClient(client_id):157def loadClient(client_id):
159 current_app.logger.debug('@oauth.clientgetter')158 current_app.logger.debug('@oauth.clientgetter')
160 #return Client.query.filter_by(id=client_id).first()159 #return Client.query.filter_by(id=client_id).first()
161 return Client.query.get(client_id)160 return Client.query.get(client_id)
162161
162
163@oauth.grantgetter163@oauth.grantgetter
164def loadGrant(client_id, code):164def loadGrant(client_id, code):
165 current_app.logger.debug('@oauth.grantgetter')165 current_app.logger.debug('@oauth.grantgetter')
166 return Grant.query.filter_by(client_id=client_id, code=code).first()166 return Grant.query.filter_by(client_id=client_id, code=code).first()
167167
168
168@oauth.grantsetter169@oauth.grantsetter
169def saveGrant(client_id, code, request, *args, **kwargs):170def saveGrant(client_id, code, request, *args, **kwargs):
170 current_app.logger.debug('@oauth.grantsetter')171 current_app.logger.debug('@oauth.grantsetter')
171 expires = datetime.utcnow() + timedelta(seconds=100)172 expires = datetime.utcnow() + timedelta(seconds=100)
172 grant = Grant(173 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
179 )180 )
180 db.session.add(grant)181 db.session.add(grant)
181 db.session.commit()182 db.session.commit()
182 return grant183 return grant
183184
185
184@oauth.tokengetter186@oauth.tokengetter
185def loadToken(access_token=None, refresh_token=None):187def loadToken(access_token=None, refresh_token=None):
186 current_app.logger.debug('@oauth.tokengetter')188 current_app.logger.debug('@oauth.tokengetter')
191 elif refresh_token:191 elif refresh_token:
192 return Token.query.filter_by(refresh_token=refresh_token).first()192 return Token.query.filter_by(refresh_token=refresh_token).first()
193193
194
194@oauth.tokensetter195@oauth.tokensetter
195def saveToken(token, request, *args, **kwargs):196def saveToken(token, request, *args, **kwargs):
196 current_app.logger.debug('@oauth.tokensetter')197 current_app.logger.debug('@oauth.tokensetter')
206 expires = datetime.utcnow() + timedelta(seconds=expires_in)206 expires = datetime.utcnow() + timedelta(seconds=expires_in)
207207
208 tok = Token(208 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
216 )216 )
217 db.session.add(tok)217 db.session.add(tok)
218 db.session.commit()218 db.session.commit()
219 return tok219 return tok
220220
221
221@oauth.usergetter222@oauth.usergetter
222def getUser():223def getUser():
223 return User.getCurrentUser()224 return User.getCurrentUser()
224225
225226
226
227# Authorized Clients227# Authorized Clients
228class AuthorizedClients(db.Model):228class AuthorizedClients(db.Model):
229 """229 """
258258
259 @staticmethod259 @staticmethod
260 def getByUser(user):260 def getByUser(user):
261 authorized_clients = [row.client for row in \
261 authorized_clients = [row.client for row in
262 AuthorizedClients.query.filter_by(user_id=user.id).all()]262 AuthorizedClients.query.filter_by(user_id=user.id).all()]
263263
264 current_app.logger.debug('authorized clients %s', authorized_clients)264 current_app.logger.debug('authorized clients %s', authorized_clients)

swtstore/classes/models/context.py

5from datetime import datetime5from datetime import datetime
6import json6import json
77
8from sqlalchemy.exc import IntegrityError
9
8from swtstore.classes import db10from swtstore.classes import db
9from swtstore.classes.models.types import JSONType11from swtstore.classes.models.types import JSONType
10from swtstore.classes.exceptions import AlreadyExistsError12from swtstore.classes.exceptions import AlreadyExistsError

swtstore/classes/models/sweet.py

8from swtstore.classes.database import db8from swtstore.classes.database import db
9# custom SQLAlchemy type JSONType9# custom SQLAlchemy type JSONType
10from swtstore.classes.models.types import JSONType10from swtstore.classes.models.types import JSONType
11from swtstore.classes.utils import urlnorm # normalize URLs
11from swtstore.classes.utils import urlnorm # normalize URLs
12from swtstore.classes.models import Context, User12from swtstore.classes.models import Context, User
13from swtstore.classes.exceptions import InvalidPayload, ContextDoNotExist
1314
15
14class Sweet(db.Model):16class Sweet(db.Model):
15 """ customary docstring """17 """ customary docstring """
1618
3232
33 created = db.Column(db.DateTime, default=datetime.utcnow)33 created = db.Column(db.DateTime, default=datetime.utcnow)
3434
35
36 def __init__(self, who, what, where, how):35 def __init__(self, who, what, where, how):
37 current_app.logger.info('initing sweet..')36 current_app.logger.info('initing sweet..')
38 self.who = who37 self.who = who
39 self.where = urlnorm(where)39 self.where = urlnorm(where)
40 self.how = how40 self.how = how
4141
42
43 def __repr__(self):42 def __repr__(self):
44 return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,43 return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
45 self.what, self.where)44 self.what, self.where)
5858
59 return None59 return None
6060
61
62 # create multiple sweets from a list of JSON61 # create multiple sweets from a list of JSON
63 @staticmethod62 @staticmethod
64 def createSweets(who, payload):63 def createSweets(who, payload):
65 # the payload has to be a list; a list of swts64 # the payload has to be a list; a list of swts
66 for each in payload:65 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\
71 mutiple sweets' % (each))70 mutiple sweets' % (each))
72 return None71 return None
7372
77 what = Context.getByName(each['what'])77 what = Context.getByName(each['what'])
7878
79 if what is None:79 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
85 current_app.logger.debug('SWEET PAYLOAD\n---\n%s\n%s\n%s\n%s\n----',83 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
88 new_sweet = Sweet(who, what, each['where'], each['how'])86 new_sweet = Sweet(who, what, each['where'], each['how'])
8987
125 #'created': self.created.isoformat()125 #'created': self.created.isoformat()
126 'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC'),126 'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC'),
127 }127 }
128
129128
130 # create and persist the sweet to the database129 # create and persist the sweet to the database
131 def persist(self):130 def persist(self):

swtstore/classes/models/types.py

3# class:: Types3# class:: Types
4# extend SQLAlchemy Types4# extend SQLAlchemy Types
55
6from datetime import datetime
7import json6import json
87
9from sqlalchemy import types8from sqlalchemy import types
9
1010
11class JSONType(types.TypeDecorator):11class JSONType(types.TypeDecorator):
12 """12 """

swtstore/classes/views/api.py

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
8from swtstore.classes.utils.httputils import makeCORSHeaders8from swtstore.classes.utils.httputils import makeCORSHeaders
9from swtstore.classes import oauth9from swtstore.classes import oauth
1010
67 payload = request.json or request.data67 payload = request.json or request.data
68 if not payload:68 if not payload:
69 current_app.logger.error('data not found in payload!')69 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!'
71 abort(400)71 abort(400)
7272
73 current_app.logger.debug('new sweet payload recvd.. %s', payload)73 current_app.logger.debug('new sweet payload recvd.. %s', payload)
7878
79 try:79 try:
80 swts = Sweet.createSweets(who, payload)80 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)
83 abort(400)83 abort(400)
8484
85 response.status_code = 20085 response.status_code = 200
99 response = makeCORSHeaders(response, origin)99 response = makeCORSHeaders(response, origin)
100100
101 if request.method == 'OPTIONS':101 if request.method == 'OPTIONS':
102 reponse.status_code = 200
102 response.status_code = 200
103 return response103 return response
104104
105 args = request.args105 args = request.args
146 current_app.logger.debug('getContextByName : %s', context)146 current_app.logger.debug('getContextByName : %s', context)
147 return jsonify(context.to_dict())147 return jsonify(context.to_dict())
148148
149
149# Get a specific context with its definition; based on id150# Get a specific context with its definition; based on id
150@api.route('/contexts/<int:id>', methods=['GET'])151@api.route('/contexts/<int:id>', methods=['GET'])
151def getContextById(id):152def getContextById(id):
194 current_app.logger.debug('new context created: %s', new_context)194 current_app.logger.debug('new context created: %s', new_context)
195195
196 # all ok. save the new context196 # all ok. save the new context
197 res = new_context.persist()
197 new_context.persist()
198198
199 response.status_code = 200199 response.status_code = 200
200 return response200 return response

swtstore/classes/views/app.py

1# -*- coding utf-8 -*-1# -*- coding utf-8 -*-
2# classes/views/apps.py2# 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
8from werkzeug.security import gen_salt7from werkzeug.security import gen_salt
98
10from swtstore.classes.models import Client, User9from swtstore.classes.models import Client, User
29 abort(404)29 abort(404)
3030
31 new_app = Client(31 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
41 )41 )
42 new_app.persist()42 new_app.persist()
4343

swtstore/classes/views/context.py

1# -*- coding utf-8 -*-1# -*- coding utf-8 -*-
2# classes/views/context.py2# 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
7from swtstore.classes.models import Context, User7from swtstore.classes.models import Context, User
88
99
10context = Module(__name__)10context = Module(__name__)
1111
12
12@context.route('/register', methods=['GET', 'POST'])13@context.route('/register', methods=['GET', 'POST'])
13def register():14def register():
14 current_user = User.getCurrentUser()15 current_user = User.getCurrentUser()
20 return render_template('context/register.html')20 return render_template('context/register.html')
2121
22 if request.method == 'POST':22 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
26 current_app.logger.debug('New Context: defn: %s ',26 current_app.logger.debug('New Context: defn: %s ',
27 request.form.get('defn'))27 request.form.get('defn'))
29 current_app.logger.debug('Resulting json_ld %s', json_ld)29 current_app.logger.debug('Resulting json_ld %s', json_ld)
3030
31 new_context = Context(31 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
35 )35 )
36 current_app.logger.debug('New Context created: %s', new_context)36 current_app.logger.debug('New Context created: %s', new_context)
37 new_context.persist()37 new_context.persist()

swtstore/classes/views/frontend.py

2# classes/views/frontend.py2# 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
11frontend = Module(__name__)10frontend = Module(__name__)
11
1212
13@frontend.route('/', methods=['GET'])13@frontend.route('/', methods=['GET'])
14def index():14def index():

swtstore/classes/views/oauth.py

1# -*- coding utf-8 -*-1# -*- coding utf-8 -*-
2# classes/views/oauth.py2# 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
8from swtstore.classes import oauth6from swtstore.classes import oauth
9from swtstore.classes.models import Client, AuthorizedClients, User7from swtstore.classes.models import Client, AuthorizedClients, User
33 else:33 else:
34 return render_template('oauth/authorize.html', **kwargs)34 return render_template('oauth/authorize.html', **kwargs)
3535
36
37 confirm = request.form.get('confirm', 'no')36 confirm = request.form.get('confirm', 'no')
38 authorized = request.form.get('authorized', 'no')37 authorized = request.form.get('authorized', 'no')
39 current_app.logger.debug('confirm authorize from user: %s', confirm)38 current_app.logger.debug('confirm authorize from user: %s', confirm)
55 #print request.form55 #print request.form
56 current_app.logger.debug('access token touched..')56 current_app.logger.debug('access token touched..')
57 return None57 return None
58
5859
59@Oauth.route('/errors')60@Oauth.route('/errors')
60def error():61def error():

swtstore/classes/views/sweet.py

2# classes/views/sweet.py2# 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
11sweet = Module(__name__)10sweet = Module(__name__)
11
1212
13@sweet.route('/<int:id>', methods=['GET'])13@sweet.route('/<int:id>', methods=['GET'])
14def showSweet(id):14def showSweet(id):

swtstore/classes/views/user.py

4import requests4import requests
55
6# flask imports6# 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
10# swtstore imports10# swtstore imports
11from swtstore.classes.models import User, Sweet, Context, Client,\11from swtstore.classes.models import User, Sweet, Context, Client,\
12 AuthorizedClients
12 AuthorizedClients
1313
14from swtstore.classes.utils.httputils import makeCORSHeaders
15from swtstore.config import DefaultConfig14from swtstore.config import DefaultConfig
1615
1716
1818
19user = Module(__name__)19user = Module(__name__)
2020
21
21@user.route('/login', methods=['POST'])22@user.route('/login', methods=['POST'])
22def login():23def login():
2324
68 response.status_code = 50068 response.status_code = 500
69 return response69 return response
7070
71
71@user.route('/logout', methods=['POST'])72@user.route('/logout', methods=['POST'])
72def logout():73def logout():
7374
82 response.status_code = 20082 response.status_code = 200
83 return response83 return response
8484
85
85@user.route('/me', methods=['GET', 'POST'])86@user.route('/me', methods=['GET', 'POST'])
86def profile():87def profile():
8788
138 apps = Client.getClientsByCreator(user.id)138 apps = Client.getClientsByCreator(user.id)
139 return render_template('user/apps.html', apps=apps)139 return render_template('user/apps.html', apps=apps)
140140
141
141@user.route('/me/authorized_apps', methods=['GET', 'POST'])142@user.route('/me/authorized_apps', methods=['GET', 'POST'])
142def authorizedApps():143def authorizedApps():
143144
149 if request.method == 'GET':149 if request.method == 'GET':
150 authorized_clients = AuthorizedClients.getByUser(user)150 authorized_clients = AuthorizedClients.getByUser(user)
151 return render_template('user/authorized_apps.html',151 return render_template('user/authorized_apps.html',
152 authorized_clients=authorized_clients)
152 authorized_clients=authorized_clients)
153153
154 # else POST request154 # else POST request
155 client_id = request.form.get('revoke-id', '')155 client_id = request.form.get('revoke-id', '')

swtstore/sample_config.py

11
2
2class DefaultConfig():3class DefaultConfig():
34
4 """5 """
21 # been done prior to editing this line.21 # been done prior to editing this line.
22 # Refer https://wiki.debian.org/PostgreSql#User_access for creating users22 # Refer https://wiki.debian.org/PostgreSql#User_access for creating users
23 # in postgresql.23 # 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
27 # Log level for the application26 # Log level for the application
28 LOG_LEVEL = 'ERROR'27 LOG_LEVEL = 'ERROR'