def create_app(config_name): app = Flask(__name__) # config app app.config.from_object(config[config_name]) # app.config.from_mapping( # SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URI'], # ) # app.config['SQLALCHEMY_ECHO'] = True # config[config_name].init_app(app) # initialize other plug-ins db.init_app(app) migrate.init_app(app, db) public_url_patterns = map(re.compile, [ '/static/', '/favicon.ico', '/logout', '/authorization_response', '/health-check', ]) json_url_patterns = map(re.compile, ['/whoami', '/api']) from app.api import api_1_0 app.register_blueprint(api_1_0, url_prefix='/api/1.0/') @app.before_request def authenticate_request(): for p in public_url_patterns: if p.match(request.path): return None # TODO: authenticate incoming request # if authenticated, set g.current_user and return None g.current_user = object() return None @app.route('/logout') def logout(): return redirect(location='/') @app.route('/authorization_response') def authorization_response(): original_url = request.args['r'] response = redirect(location=original_url) return response @app.route('/health-check') def health_check(): return make_response('OK', 200, {'Content-Type': 'text/plain'}) return app
def db(app, request): _db.init_app(app) # create schema _db.drop_all() _db.create_all() # seed database seed_migrate = SeedMigrate(app, _db) seed_migrate.update() # add sample data add_sample_data(_db.session) _db.session.commit() request.addfinalizer(lambda: _db.drop_all()) return _db
def create(): app = Flask(__name__) app.config.from_object(config) from api_legacy import api_legacy from api_native import api_native from files import files from frontend import frontend app.register_blueprint(api_legacy, url_prefix='/api') app.register_blueprint(api_native) app.register_blueprint(files) app.register_blueprint(frontend) from db import models, database database.init_app(app) database.database.create_tables(models, safe=True) if config.FLASK_PROXY: app.wsgi_app = ProxyFix(app.wsgi_app) return app
def create_app(config_name, debug=False): app = Flask(__name__) app.debug = debug app.config.from_object(config[config_name]) config[config_name].init_app(app) database.init_app(app) socketio.init_app(app) SS = database.session from .views import views app.register_blueprint(views, url_prefix='') @app.teardown_request def terminate_transaction(exception=None): if exception: SS.rollback() else: SS.commit() return app
import datetime from flask import Flask, render_template, request, redirect, session #this is for calling the database from db import database from models import Home, Blog #create the application object app = Flask(__name__) app.config.from_object('config') database.init_app(app) @app.route("/") def homepage(): #nama_table = Class.query.filter.by ikuti selanjutnya home = Home.query.filter_by(id=1).first() return render_template("index.html", **locals()) @app.route("/blog") def blogpage(): blog = Blog.query.all() return render_template("blog.html", **locals()) #show content by id @app.route("/blog/<int:id>") def show_content(id): # Post.query.get(id) == select*from blog(tablename) where id = '' blog = Blog.query.get(id) if not blog: abort(404) return render_template("blogpost.html", **locals())
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) # app.wsgi_app = MyAuthMiddleWare(app.wsgi_app, # app.config['AUTHENTICATION_LOGIN_URL'], # public_prefixes=['/static/', '/favicon.ico', '/logout'], # json_prefixes=['/api/'], # ) from app.api import api_1_0 app.register_blueprint(api_1_0, url_prefix='/api/1.0/') # @app.before_request # def get_current_user(): # data = request.environ.get('myauthmiddleware', None) # if data and data['REMOTE_USER_ID']: # user = m.User.query.get(data['REMOTE_USER_ID']) # else: # user = m.User.query.get(1) # session['current_user'] = user # @app.after_request # def clear_current_user(resp): # session['current_user'] = None # return resp # @app.teardown_request # def terminate_transaction(exception): # if exception is None: # SS.commit() # else: # SS.rollback() # SS.remove() @app.route('/') def index(): return send_file(os.path.join(os.path.dirname(__file__), 'index.html')) @app.route('/favicon.ico') def favicon(): return send_file(os.path.join(os.path.dirname(__file__), 'favicon.ico')) @app.route('/whoami') def whoami(): return jsonify(message=os.environ.get('AWS_ENV', 'unknown')) @app.route('/hello') def hello(): return jsonify(message='hello, world.') @app.errorhandler(404) def default_hander(exc): if request.path.startswith('/static'): return make_response( _('Sorry, the resource you have requested for is not found'), 404) # TODO: only redirect valid urls return redirect('/#%s' % request.path) return app
#estantevirtual resources api.add_resource(EVBooks, '/estantevirtual') #book resources api.add_resource(Books, '/books') api.add_resource(BooksAuthors, '/books') api.add_resource(Book, '/books/<string:id_book>') #users resources api.add_resource(Users, '/users') api.add_resource(User, '/users/<string:username>') api.add_resource(UserRegister, '/users/register') api.add_resource(UserAuth, '/authorization') api.add_resource(UserLogout, '/logout') #author resources api.add_resource(Authors, '/authors') api.add_resource(Author, '/authors/<string:id_author>') #edtions resources api.add_resource(Edtions, '/edtions') api.add_resource(Edtion, '/edtions/<string:id_edtion>') #sellers resources api.add_resource(Sellers, '/sellers') if __name__ == "__main__": from db import database database.init_app(app) app.run(host='127.0.0.1', port='8080', debug=True)
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) audio_server.init_app( app, lambda: create_access_token(int(app.config["ADMIN_APPEN_ID"]))) pdb.init_app( app, lambda: create_access_token(int(app.config["ADMIN_APPEN_ID"]))) CORS(app, resources={'/api/1.0/*': {'origins': '*'}}) logging.basicConfig(level=app.config["LOG_LEVEL"]) public_url_patterns = map(re.compile, [ '/static/', '/favicon.ico', '/edm', '/webservices', '/logout', '/authorization_response', '/health-check', "/api/1.0/status", "/api/1.0/get-token", ]) json_url_patterns = map(re.compile, ['/whoami', '/api']) from app.api import api_1_0 from app.edm import edm from app.tagimages import tagimages from app.webservices import webservices from app.views import views app.register_blueprint(api_1_0, url_prefix='/api/1.0/') app.register_blueprint(edm, url_prefix='/edm') app.register_blueprint(tagimages, url_prefix='/tagimages') app.register_blueprint(webservices, url_prefix='/webservices') app.register_blueprint(views, url_prefix='') oauth = OAuth() soteria = oauth.remote_app( 'soteria', base_url=None, request_token_url=None, access_token_url=app.config['OAUTH2_TOKEN_ENDPOINT'], authorize_url=app.config['OAUTH2_AUTHORIZATION_ENDPOINT'], consumer_key=app.config['OAUTH2_CLIENT_ID'], consumer_secret=app.config['OAUTH2_CLIENT_SECRET'], request_token_params={ 'scope': 'user', 'state': 'blah' }, ) @app.before_request def authenticate_request(): # current_app.logger.debug('{} {}'.format(request.method, request.url)) # do not authenticate public urls for p in public_url_patterns: if p.match(request.path): # current_app.logger.debug(\ # 'skip authencation for public url: {}'\ # .format(request.url)) return None # current_app.logger.debug('{} {}'.format(request.method, request.url)) if not current_app.config['SSO_COOKIE_NAME']: check = lambda (x): True else: try: sso_cookie = request.cookies.get( current_app.config['SSO_COOKIE_NAME']) appenId = jwt.decode( sso_cookie, current_app.config['APPEN_API_SECRET_KEY'])['appen_id'] check = lambda (x): appenId == int(x) except: check = lambda (x): False # authenticate by cookie try: cookie_name = current_app.config['APP_COOKIE_NAME'] cookie = request.cookies.get(cookie_name) if not cookie: raise RuntimeError('cookie {} not found'\ .format(cookie_name)) secret = current_app.config['APP_COOKIE_SECRET'] try: user_dict = auth.decode_cookie(cookie, secret) if not check(user_dict['REMOTE_USER_ID']): # current_app.logger.debug('gnx cookie stale') raise RuntimeError('gnx cookie is stale') user = m.User.query.get(user_dict['REMOTE_USER_ID']) session['current_user'] = user session['current_user_caps'] = user_dict['CAPABILITIES'] session['current_user_type'] = user_dict['USER_TYPE'] session['current_user_roles'] = user_dict['ROLES'] return None except: raise RuntimeError('cookie corrupted or expired') except RuntimeError, e: # current_app.logger.debug('cookie authentication failed: {}'\ # .format(e)) pass # authenticate by header try: authorization_info = request.headers.get('authorization', None) # current_app.logger.debug('authorization header: {}'\ # .format(authorization_info)) if not authorization_info: raise RuntimeError('authorization header not found') try: globalId, token = authorization_info.split('~', 1) except: raise RuntimeError('unknown header format: {}'\ .format(authorization_info)) try: result = util.go.check_token_for_user(globalId) current_app.logger.debug('token info: {}'.format(result)) # result = { # 'token': token, # 'expires_at': 'something', # 'appen_id': 15517, # 'app_id': 'appen_global' # } except RuntimeError, e: # token validation failed, return 500 to indicate server error return make_response(jsonify(error=\ _('token validation failed: {}').format(e), ), 500) token_should_be = result.get('token', None) if token != token_should_be: raise RuntimeError(\ 'token validation failed: expecting {}, got {}'\ .format(token_should_be, token)) current_app.logger.debug( 'token validation passed, add user if necessary') try: user = m.User.query.filter(m.User.globalId == globalId).one() current_app.logger.debug('found local user {}'\ .format(user.emailAddress)) except NoResultFound: SS.rollback() current_app.logger.debug(\ 'user {} not found, get it from edm'.format(globalId)) try: user = util.edm.make_new_user(globalId) SS.add(user) SS.flush() SS.commit() except Exception, e: SS.rollback() current_app.logger.error(\ 'failed to add user locally: {}'.format(e)) return make_response(\ jsonify(error=_('failed to add user {} locally'\ ).format(globalId), ), 500)
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) CORS(app, resources={'/api/1.0/*': {'origins': '*'}}) app.wsgi_app = MyAuthMiddleWare( app.wsgi_app, app.config['AUTHENTICATION_LOGIN_URL'], public_prefixes=[ '/static/', '/favicon.ico', '/health-check', '/logout' ], json_prefixes=['/api/', '/whoami'], ) from app.api import api_1_0 app.register_blueprint(api_1_0, url_prefix='/api/1.0/') @app.before_request def set_current_user(): data = request.environ.get('myauthmiddleware', None) g.current_user = None if data: userId = int(data['REMOTE_USER_ID']) g.current_user = m.User.query.get(userId) # @app.teardown_request # def terminate_transaction(exception): # if exception is None: # SS.commit() # else: # SS.rollback() # SS.remove() # @app.errorhandler(404) # def default_hander(exc): # if request.path.startswith('/static'): # return make_response( # _('Sorry, the resource you have requested for is not found'), # 404) # if request.path.startswith('/api/'): # return make_response(jsonify(error='requested url not found'), # 404, {}) # # TODO: only redirect valid urls # return redirect('/#%s' % request.path) @app.route('/whoami') def who_am_i(): me = g.current_user resp = jsonify(user=m.User.dump(me)) resp.headers['Cache-Control'] = 'max-age=0, must-revalidate' return resp @app.route('/health-check') def health_check(): return make_response('OK', 200, {'Content-Type': 'text/plain'}) @app.route('/logout') def logout(): @after_this_request def clear_cookie(resp): resp.set_cookie(os.environ['APP_COOKIE_NAME']) return resp return redirect(app.config['AUTHENTICATION_LOGIN_URL']) @app.route('/') def index(): fpath = os.path.join(os.path.dirname(__file__), 'index.html') return send_file(fpath) return app