def test_register_callback_works(self): call_history = [] def callback(obj_response): call_history.append('callback') obj_response.alert('test') app = flask.Flask(__name__) helper = flask_sijax.Sijax(app) with app.test_request_context(): app.preprocess_request() helper.register_callback('test', callback) # no data, cannot determine request as a sijax request self.assertFalse(helper.is_sijax_request) cls_sijax = helper._sijax.__class__ helper._sijax.set_data({cls_sijax.PARAM_REQUEST: 'test', cls_sijax.PARAM_ARGS: '[]'}) self.assertTrue(helper.is_sijax_request) response = helper.process_request() self.assertEqual(['callback'], call_history) _assert_response_json(self, response)
def test_upload_callbacks_receive_the_expected_arguments(self): # Upload callbacks should have the following signature: # def function(obj_response, flask_request_files, form_values) # The extension should ensure that the proper arguments are passed import sijax from types import GeneratorType app = flask.Flask(__name__) helper = flask_sijax.Sijax(app) call_history = [] def callback(obj_response, files, form_values): call_history.append(form_values) call_history.append(id(files)) with app.test_request_context(): app.preprocess_request() helper.register_upload_callback('form_id', callback) func_name = sijax.plugin.upload.func_name_by_form_id('form_id') cls_sijax = helper._sijax.__class__ post = {cls_sijax.PARAM_REQUEST: func_name, cls_sijax.PARAM_ARGS: '["form_id"]', 'post_key': 'val'} helper._sijax.set_data(post) self.assertTrue(helper.is_sijax_request) response = helper._sijax.process_request() self.assertTrue(isinstance(response, GeneratorType)) for r in response: pass expected_history = [{'post_key': 'val'}, id(flask.request.files)] self.assertEqual(expected_history, call_history)
def setup(): if 'syslog' in args.log: # log to syslog logging.basicConfig( level=logging.DEBUG, format="[%(asctime)s][%(module)s][%(levelname)s] => %(message)s", handlers=[ logging.handlers.RotatingFileHandler( '/var/log/livolo_ble_webpanel.log', maxBytes=500000, backupCount=5) ]) else: logging.basicConfig( level=logging.DEBUG, format="[%(asctime)s][%(module)s][%(levelname)s] => %(message)s") signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGTERM, sigterm_handler) load_flask_app_configs(read_config_file_settings(args.config)) flask_sijax.Sijax(app) global app_cfg_check_t app_cfg_check_t = threading.Thread(target=app_cfg_check) app_cfg_check_t.setDaemon(True) app_cfg_check_t.start() # synchronize file config change checker thread with write operations on it # very important - unwanted things can happen otherwise global ini_file_write ini_file_write = threading.Condition()
def create_app(config_name): app = Flask(__name__) app.debug = True app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) pagedown.init_app(app) celery.conf.update(app.config) if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask_sslify import SSLify sslify = SSLify(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from .api_1_0 import api as api_1_0_blueprint app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0') app.config['SIJAX_STATIC_PATH'] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/') app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' flask_sijax.Sijax(app) return app
def test_request_uri_changing_works(self): # The request URI is automatically detected, # but could be changed to something else on each request # Changes should not be preserved throughout different requests though app = flask.Flask(__name__) helper = flask_sijax.Sijax(app) with app.test_request_context(): app.preprocess_request() js = helper.get_js() self.assertTrue('Sijax.setRequestUri("/");' in js) helper.set_request_uri('http://something.else/') js = helper.get_js() self.assertFalse('Sijax.setRequestUri("/");' in js) self.assertTrue('Sijax.setRequestUri("http://something.else/");' in js) # Ensure that the changed request uri was valid for the previous request only with app.test_request_context(): app.preprocess_request() js = helper.get_js() self.assertTrue('Sijax.setRequestUri("/");' in js) self.assertFalse('Sijax.setRequestUri("http://something.else/");' in js) # Test that a more complex request url (with query string, etc) works with app.test_request_context('/relative/url?query=string&is=here'): app.preprocess_request() js = helper.get_js() self.assertTrue('Sijax.setRequestUri("/relative/url?query=string&is=here");' in js)
def create_app(config=None): app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) app.wsgi_app = ProxyFix(app.wsgi_app) db.init_app(app) if app.debug is True: try: from flask_debugtoolbar import DebugToolbarExtension toolbar = DebugToolbarExtension(app) except: pass with app.test_request_context(): db.create_all() from .general import controllers as general from .shop import controllers as shop from .test import controllers as test app.register_blueprint(shop.module) app.register_blueprint(general.module) app.register_blueprint(test.module) flask_sijax.Sijax(app) return app
def test_delayed_app_initialization_works(self): # Makes sure that an app object can be provided at a later point # and that Sijax would still be registered correctly. app = flask.Flask(__name__) helper = flask_sijax.Sijax() helper.init_app(app) with app.test_request_context(): app.preprocess_request() self.assertEqual(id(helper), id(flask.g.sijax))
def test_sijax_helper_passes_correct_post_data(self): # It's expected that the Sijax Helper class passes `flask.request.form` # as post data in the "on before request" stage app = flask.Flask(__name__) helper = flask_sijax.Sijax(app) with app.test_request_context(): app.preprocess_request() self.assertEqual(id(helper._sijax.get_data()), id(flask.request.form))
def test_registering_callbacks_in_a_non_request_context_fails(self): app = flask.Flask(__name__) helper = flask_sijax.Sijax(app) try: helper.register_callback('test', lambda r: r) self.fail('Callback registered, but failure was expected!') except AttributeError: # helper._sijax (and flask.g.sijax) pass
def test_json_uri_config_is_used(self): uri = '/some/json_uri.here' app = flask.Flask(__name__) app.config['SIJAX_JSON_URI'] = uri helper = flask_sijax.Sijax(app) with app.test_request_context(): app.preprocess_request() js = helper.get_js() self.assertTrue(uri in js)
def _prepare_app(): """ Setup the initial APP values and initialize various flask plugins. :returns: flask app instance """ # init JSGLUE. this is needed to query URLs in javascript _js_glue = JSGlue(APP) cfg_rdr = ConfigReader() APP.config['SECRET_KEY'] = cfg_rdr.get_attr('db_secret_key') APP.config['SQLALCHEMY_DATABASE_URI'] = cfg_rdr.get_attr('db_address') # needed because this functionality is already depricated APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # the salt is a workaround for a bug, as flask-security salts passwords # automatically but somehow it requires and uses this config value which # breaks the login if the salt is individually unique (as a salt should be) APP.config['SECURITY_PASSWORD_SALT'] = 'fake_salt' APP.config['SECURITY_TRACKABLE'] = True APP.config['SECURITY_REGISTERABLE'] = True APP.config['SECURITY_CONFIRMABLE'] = False APP.config['UPLOAD_FOLDER'] = 'config' # max upload size is 50 KB APP.config['MAX_CONTENT_LENGTH'] = 50 * 1024 path = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/') APP.config['SIJAX_STATIC_PATH'] = path APP.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' flask_sijax.Sijax(APP) APP.config['JWT_ALGORITHM'] = 'RS256' with open(cfg_rdr.get_attr('private_key_file_location'), 'rb') as file: APP.config['JWT_PRIVATE_KEY'] = file.read() JWT = JWTManager(APP) with APP.app_context(): DB.init_app(APP) user_datastore = SQLAlchemyUserDatastore(DB, User, Role) _security = Security(APP, user_datastore) setup(user_datastore) rs256_token = create_access_token(str(current_user), expires_delta=False) APP.config['access_headers'] = {'Authorization': 'Bearer {}' .format(rs256_token)} JSONService.init(APP.config['access_headers']) return APP
def create_app(config_name): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile('config.py') db.init_app(app) migrate = Migrate(app, db) login_manager.init_app(app) bcrypt.init_app(app) #Sijax app.config['SIJAX_STATIC_PATH'] = path app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' flask_sijax.Sijax(app) #Login manager use login_manager.login_message = "Veuillez vous connecté" login_manager.login_view = "auth.user_login" login_manager.login_message_category = 'danger' from app import models #Authentification from .authentification import auth as auth_blueprint app.register_blueprint(auth_blueprint) #User from .user import user as user_blueprint app.register_blueprint(user_blueprint) #User from .main import main as main_blueprint app.register_blueprint(main_blueprint) #Categorie from .categorie import categorie as categorie_blueprint app.register_blueprint(categorie_blueprint) #Produit from .produit import produit as produit_blueprint app.register_blueprint(produit_blueprint) #Internaute from .internaute import internaute as internaute_blueprint app.register_blueprint(internaute_blueprint) #Client from .client import client as client_blueprint app.register_blueprint(client_blueprint) return app
def createApp(configuration=None): global app app = Flask(__name__) configureApp(app, configuration) configureJinja(app, version) configureLogging(app) db.init_app(app) bcrypt.init_app(app) loginManager.init_app(app) oauth.init_app(app) loginManager.init_app(app) MimicDB() # This allows Sijax to keep the JS files up to date app.config['SIJAX_STATIC_PATH'] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/') flask_sijax.Sijax(app) if app.config['MIGRATE_PRODUCTION']: migrate = Migrate(app, db, directory='/home/ubuntu/revisify/migrations') else: migrate = Migrate(app, db) import hooks import views import views.errors views = ( views.account, views.admin, views.confirmation, views.footer, views.help, views.static, views.main, views.signInOauth, views.password, views.settings, views.social, views.subject, views.study, views.topic ) for view in views: app.register_blueprint(view) return app
def test_sijax_helper_object_is_only_bound_to_g_in_a_request_context(self): app = flask.Flask(__name__) helper = flask_sijax.Sijax(app) with app.test_request_context(): app.preprocess_request() self.assertEqual(id(helper), id(flask.g.sijax)) # Make sure that access fails when outside of a request context try: flask.g.sijax except RuntimeError: # RuntimeError('working outside of request context') pass else: self.fail('Bound to g in a non-request context!')
def create_app(config_name): app = Flask(__name__) app.debug = True app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 moment.init_app(app) pagedown.init_app(app) if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask_sslify import SSLify sslify = SSLify(app) app.config['SIJAX_STATIC_PATH'] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/') app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' flask_sijax.Sijax(app) return app
def create_app(config='planlos.config.Config'): app = Flask('planlos') app.config.from_object(config) db.init_app(app) mail.init_app(app) flask_sijax.Sijax(app) # Flask Login login_manager.setup_app(app) app.register_blueprint(base, url_prefix='/') app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(calendar, url_prefix='/events') app.register_blueprint(accounts, url_prefix='/users') app.register_blueprint(locations, url_prefix='/locations') app.register_blueprint(webservice, url_prefix='/webservice') app.register_blueprint(groups, url_prefix='/groups') app.jinja_env.globals['widget'] = widget user_logged_in.connect(set_login_stamp, app) return app
def test_process_request_returns_a_string_or_a_flask_response_object(self): # flask_sijax.Sijax.process_request should return a string for regular functions # and a Flask.Response object for functions that use a generator (streaming functions) from sijax.response import StreamingIframeResponse app = flask.Flask(__name__) helper = flask_sijax.Sijax(app) with app.test_request_context(): app.preprocess_request() cls_sijax = helper._sijax.__class__ post = {cls_sijax.PARAM_REQUEST: 'callback', cls_sijax.PARAM_ARGS: '[]'} helper._sijax.set_data(post) helper.register_callback('callback', lambda r: r) response = helper.process_request() self.assertTrue(isinstance(response, type('string'))) helper.register_callback('callback', lambda r: r, response_class=StreamingIframeResponse) response = helper.process_request() self.assertTrue(isinstance(response, flask.Response))
flask_socket = socket.socket() flask_socket.bind(('', 0)) flask_port = flask_socket.getsockname()[1] flask_socket.close() print('BrainDir Uploader is running on port: ' + str(flask_port)) ######################### Flask code ######################### # initialise app flask_app = Flask(__name__, template_folder=templates_path, static_folder=static_path) # config for flask-sijax flask_app.config["CACHE_TYPE"] = "null" flask_app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0 flask_sijax.Sijax(flask_app) class SijaxHandler(object): @staticmethod def update_pgb(obj_response, up_prog_filename): upload_progress_file_path = os.path.join(appdata_path, 'files', up_prog_filename) with open(upload_progress_file_path, 'r+b') as upf: upload_prog_dict = json.load(upf) total_bytes = upload_prog_dict['total_bytes_to_upload'] current_bytes = upload_prog_dict['bytes_uploaded'] progress = current_bytes * 100 / total_bytes progress_str = str(progress) + '%' print(progress_str)
def create_app(): # init app app = Flask(__name__, template_folder='templates') api = Api(app) # enable debug app.debug = True # set configuration mode to development app.config.from_object(config.DevelopmentConfig) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['JWT_BLACKLIST_ENABLED'] = False app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] # init db db.init_app(app) # needed for pgsql migration script migrate = Migrate(app, db) @app.before_first_request def create_tables(): db.create_all() login_manager = LoginManager() login_manager.login_view = 'pages.login_page' login_manager.init_app(app) from .model.pgsql import User # flask_login recommended to load current user @login_manager.user_loader def load_user(user_id): return User.User.query.get(int(user_id)) # register blueprints # from app.bot.TelegramBot import bot_father as bot_father_blueprint # app.register_blueprint(bot_father_blueprint) from .auth_ui import auth_ui as auth_ui_blueprint app.register_blueprint(auth_ui_blueprint) from app.api.auth_api import auth_api as auth_api_blueprint app.register_blueprint(auth_api_blueprint) from app.api.routes_api import routes_api as routes_api_blueprint app.register_blueprint(routes_api_blueprint) from .pages_ui import pages_ui as pages_blueprint app.register_blueprint(pages_blueprint) from app.specific.conversion import conversion as conversion_blueprint app.register_blueprint(conversion_blueprint) # from app.specific.botadmin import botadmin as botadmin_blueprint # app.register_blueprint(botadmin_blueprint) # add jwt support on app app.config['JWT_SECRET_KEY'] = 'jwt-secret-string' app.config['JWT_BLACKLIST_ENABLED'] = False jwt = JWTManager(app) # sijax support # The path where you want the extension to create the needed javascript files # DON'T put any of your files in this directory, because they'll be deleted! app.config["SIJAX_STATIC_PATH"] = basedir + '/static/js/sijax/' # You need to point Sijax to the json2.js library if you want to support # browsers that don't support JSON natively (like IE <= 7) app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js' flask_sijax.Sijax(app) # ajax csrf security token @app.template_global('csrf_token') def csrf_token(): if "_csrf_token" not in fsession: fsession["_csrf_token"] = os.urandom(128) return hmac.new(b'config.Config.SECRET_KEY', fsession["_csrf_token"]).hexdigest() # init socket io # manager = RedisManager('redis://') # Server(client_manager=manager) return app
def create_app(): app = Flask( __name__, template_folder='./templates', static_folder='./static' ) # config app_settings = os.getenv('APP_SETTINGS', 'app.config.DevelopmentConfig') app.config.from_object(app_settings) # set up extensions db.init_app(app) migrate.init_app(app, db) # register Blueprint from app.views import index app.register_blueprint(index.app, url_prefix='') # Jinja2 app.jinja_env.filters['strftime'] = date_format # Sijax flask_sijax.Sijax(app) # log # @app.before_first_request # def make_logger(): # handler = RotatingFileHandler('server_log.log', maxBytes=100000, backupCount=5) # handler.setFormatter(Formatter("[%(asctime)s] %(levelname)s - %(message)s")) # # current_app.logger.addHandler(handler) # current_app.logger.setLevel(INFO) # # current_app.logger.info('------- Logger Initialized -------') # # @app.before_request # def before_request(): # current_app.logger.info('Request from {0} [ {1} {2} ]'.format(request.host, request.method, request.url)) # current_app.logger.info('Request values : '.format(request.values)) # # @app.after_request # def after_request(response): # current_app.logger.info('Respond : {0}'.format(response.status)) # # response.headers['X-Powered-By'] = app.config['SERVICE_NAME'] # # return response # # @app.teardown_appcontext # def teardown_appcontext(exception): # if not exception: # current_app.logger.info('Teardown appcontext successfully.') # error handler @app.errorhandler(403) def handle_403(e): return render_template('403.html') @app.errorhandler(404) def handle_404(e): return render_template('404.html') @app.errorhandler(500) def handle_500(e): return render_template('500.html') return app
def initialize_extensions(app): # Since the application instance is now created, pass it to each Flask # extension instance to bind it to the Flask application instance (app) db.init_app(app) sjx = flask_sijax.Sijax(app)
def make_app(debug=False, **app_options): global db, app, admin app = Flask(__name__) logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) logg.debug("creating flask app %s", __name__) try: import arguments.config app.config.from_object(arguments.config) except ImportError: pass if app_options: app.config.update(app_options) app.config["RESTFUL_JSON"] = {'ensure_ascii': False} app.config["SECRET_KEY"] = "dev" app.config["DEBUG"] = debug logg.debug("app config is:\n%s", pformat(dict(app.config))) if debug: app.debug = True from werkzeug.debug import DebuggedApplication app.wsgi_app = DebuggedApplication(app.wsgi_app, True) app.jinja_env.add_extension('arguments.helper.templating.PyJadeExtension') # initialize extensions # flask-sqlalchemy db = SQLAlchemy(app) import arguments.database.datamodel # flask-admin admin = Admin(app, name="Arguments", template_mode="bootstrap3") # markdown via flask-misaka # TODO: markdown options should be configurable markdown_opts = dict( autolink=True, fenced_code=True, no_intra_emphasis=True, strikethrough=True, tables=True, safelink=True, escape=True, smartypants=True ) Misaka(app, **markdown_opts) # user management provided by flask_login login_manager = LoginManager(app) login_manager.login_view = 'ekklesia.login' # XXX: for testing: just use first user from the DB as anon user # login_manager.anonymous_user = lambda: User.query.first() from arguments.database.datamodel import User @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # i18n via flask-babelex babel = Babel(app) @babel.localeselector def get_locale(): return session["locale"] # OAuth2 using flask-dance init_oauth_ext(app) # ajax lib flask-sijax path = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/') app.config['SIJAX_STATIC_PATH'] = path app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' flask_sijax.Sijax(app) @app.before_request def set_locale(): locale = session.get("locale") if locale: logg.debug("locale from session: %s", locale) else: locale = request.accept_languages.best_match(['de', 'en', 'fr']) logg.debug("locale from request: %s", locale) session["locale"] = locale g.locale = locale import arguments.views import arguments.views.admin # import arguments_rest.api # needed when running behind a reverse proxy. app.wsgi_app = ProxyFix(app.wsgi_app) return app
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy import flask_sijax ####################### #### Configuration #### ####################### # Create the instances of the Flask extensions (flask-sqlalchemy, flask-login, etc.) in # the global scope, but without any arguments passed in. These instances are not attached # to the application at this point. db = SQLAlchemy() sjx = flask_sijax.Sijax() ###################################### #### Application Factory Function #### ###################################### def create_app(config_filename=None): app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile(config_filename) # The path where you want the extension to create the needed javascript files # DON'T put any of your files in this directory, because they'll be deleted! app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/') # You need to point Sijax to the json2.js library if you want to support # browsers that don't support JSON natively (like IE <= 7)
def create_app(config_name): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile( 'config.py') app.config.from_mapping( CLOUDINARY_URL=os.environ.get('CLOUDINARY_URL') or 'Pegue a sua Key', ) # #Bootstrap(app) db.init_app(app) bcrypt.init_app(app) login_manager.init_app(app) migrate = Migrate(app, db) #Sijax app.config['SIJAX_STATIC_PATH'] = path app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' flask_sijax.Sijax(app) login_manager.login_message = "Veuillez vous connecté" login_manager.login_view = "auth.login" login_manager.login_message_category ='danger' #SimpleMDE(app) #md= Markdown(app, extensions=['fenced_code']) from app import models ''' Utilisation des stucture Blueprint ''' # @app.errorhandler(403) # def forbidden(error): # return render_template('errors/403.html', title='Forbidden'), 403 # @app.errorhandler(404) # def page_not_found(error): # return render_template('errors/404.html', title='Page non trouvée'), 404 # @app.errorhandler(500) # def internal_server_error(error): # return render_template('errors/500.html', title='Erreur serveur'), 500 #Authentification from .authentification import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .categorie import categorie as categorie_blueprint app.register_blueprint(categorie_blueprint) from .user import user as user_blueprint app.register_blueprint(user_blueprint) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .publication import publication as publication_blueprint app.register_blueprint(publication_blueprint) from .asdi import asdi as asdi_blueprint app.register_blueprint(asdi_blueprint) from .promotion import promotion as promotion_blueprint app.register_blueprint(promotion_blueprint) from .categorieMusique import categorieMusique as categorieMusique_blueprint app.register_blueprint(categorieMusique_blueprint) from .play_list import play_list as play_list_blueprint app.register_blueprint(play_list_blueprint) from .internaute import internaute as internaute_blueprint app.register_blueprint(internaute_blueprint) return app
from flask import Flask, g from flask_bcrypt import Bcrypt from pymongo import MongoClient from flask_login import LoginManager import os import flask_sijax path = os.path.join('.', os.path.dirname(__file__), 'static\\js\\sijax\\') app = Flask(__name__) app.config['SECRET_KEY'] = 'fd141cbd0c454da349011c867da4b3db' app.config['SIJAX_STATIC_PATH'] = path app.config['SIJAX_JSON_URI'] = '\\static\\js\\sijax\\json2.js' flask_sijax.Sijax(app) #client = MongoClient('localhost', 27017) client = MongoClient('mongodb://*****:*****@clustermdb-shard-00-00-gg5i3.gcp.mongodb.net:27017,clustermdb-shard-00-01-gg5i3.gcp.mongodb.net:27017,clustermdb-shard-00-02-gg5i3.gcp.mongodb.net:27017/test?ssl=true&replicaSet=ClusterMDB-shard-0&authSource=admin&retryWrites=true') db = client.cuidas bcrypt = Bcrypt(app) login_manager = LoginManager(app) login_manager.login_view = 'login' login_manager.login_message_category = 'info' from cuidas_app import routes
def create_app_new(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Bootstrap(app) flask_sijax.Sijax(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/', methods=('GET', 'POST')) def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser flash('critical message', 'critical') flash('error message', 'error') flash('warning message', 'warning') flash('info message', 'info') flash('debug message', 'debug') flash('different message', 'different') flash('uncategorized message') return render_template('index.html', form=form) @app.route('/congrats') def congrats(): return render_template('congrats.html') @app.route('/wrong') def wrong(): return render_template('wrong.html') @app.route('/quiz') def quiz(): qid = random.sample(range(len(qa_set.keys())), 1)[0] contents, question, answer, score = qa_set[qid] correct_count = 0 if request.args.get('correct_count'): correct_count = int(request.args.get('correct_count')) ai_correct_count = 0 if request.args.get('ai_correct_count'): ai_correct_count = int(request.args.get('ai_correct_count')) correct_qids = [] if correct_count > 0: if request.args.get('correct_qids'): correct_qids = request.args.get('correct_qids').split(',') print(correct_qids) while (str(qid) in correct_qids): qid = random.sample(range(len(qa_set.keys())), 1)[0] # for key in request.args.keys(): # print(key + ' ' + request.args.get(key)) # print(int(request.args.get('ai_correct_count'))) # print return render_template('quiz.html', contents=contents, qid=qid, question=question, correct_count=correct_count, ai_correct_count=ai_correct_count, correct_qids=','.join(correct_qids)) # @flask_sijax.route(app, '/result') @app.route('/result', methods=['POST']) def result(): # Every Sijax handler function (like this one) receives at least # one parameter automatically, much like Python passes `self` # to object methods. # The `obj_response` parameter is the function's way of talking # back to the browser # def say_hi(obj_response): # obj_response.alert('Hi there!') correct_count = int(request.form['correct_count']) ai_correct_count = int(request.form['ai_correct_count']) correct_qids = request.form['correct_qids'].split(',') #ai_correct_count = int(request.form['ai_correct_count']) qid = request.form['qid'] answer = request.form['answer'] ai_answer = qa_set[int(qid)][3] correct_answer = qa_set[int(qid)][2] result_message = '' animation = '' ai_result = '' human_result = '' if ai_answer == correct_answer: ai_result = 'correct' ai_correct_count = ai_correct_count + 1 else: ai_result = 'wrong' if correct_answer == answer: result_message = '정답이에요~'; animation = 'pulse slow'; human_result = 'correct' correct_count = correct_count + 1 if correct_qids == ['']: correct_qids = [qid] else: correct_qids.append(qid) else: result_message = '땡! 기계보다 못한..' animation = 'hinge delay-2s' human_result = 'wrong' correct_qids = [] result = str(correct_answer==answer) # if g.sijax.is_sijax_request: # # Sijax request detected - let Sijax handle it # g.sijax.register_callback('say_hi', say_hi) # return g.sijax.process_request() # Regular (non-Sijax request) - render the page template return render_template('result.html', result_message=result_message, correct_answer=correct_answer, animation=animation, ai_result=ai_result, human_result=human_result, answer=answer, correct_count=correct_count, ai_correct_count=ai_correct_count, result=(correct_answer==answer), ai_answer=ai_answer, correct_qids=','.join(correct_qids)) #return json.dumps({'result_message':result_message,'correct_answer':correct_answer,'animation':animation}); return app