def create_app(app_mode='DEBUG'): """ Create application, register blueprints, etc """ # create an application app = Flask(__name__) # set logging if app_mode == '': app_mode = os.environ.get('APP_MODE', 'DEBUG') if app_mode == 'PROD': app.config.from_object(ProductionConfig) #create_rotating_log(app, 'app.log') logging.basicConfig( filename='app.log', format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG) elif app_mode == 'OPENSHIFT': app.config.from_object(OpenshiftConfig) logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s' ) else: #app.debug_log_format = '%(asctime)s %(levelname)s %(message)s' #app.logger.setLevel(logging.DEBUG) logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s' ) app.config.from_object(Config) logging.debug('Starting app in %s mode' % app_mode) # register blueprints app.register_blueprint(ui) #register jinja2 functions app.jinja_env.globals.update(max=max) # set secret for sessions app.secret_key = 'Qm9enl7mikELxCbcMvsP' # set login manager app.users = dict() login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = '/auth' login_manager.user_callback = user_loader # register flask-debugtoolbar if app_mode == 'DEBUG': app.dtb = DebugToolbarExtension(app) # init tinydb app.repo = Repository() app.repo.init_db(app.config['TINYDB_FILE']) # init WgDataProvider WgDataProvider.APP_ID = app.config['APP_ID'] WgDataProvider.CACHE_DIR = app.config['CACHE_DIR'] return app
def create_app(options): app = Flask(__name__) app.secret_key = 'ed788cab1d449175885623bf5fad28101898b059380a263f' config = ConfigParser.ConfigParser() config.readfp(open(options.config)) app.mopts = misc.MagicOptions(config_defaults, dict(config.items(options.section)), vars(options), dict(section=options.section)) app.users = dict(config.items('users_' + options.section)) engine = create_engine(app.mopts.uri) adjust_schemas(staging=app.mopts.staging_schema, model=app.mopts.model_schema) Session = sessionmaker(bind=engine) # autocommit=True) auth.init_login_manager(app) jinja_local.jinja_filters.init_app(app) misc.menu.init_app(app) app.register_blueprint(auth.auth) # app.register_blueprint(errors.errors) app.register_blueprint(home.homebp, url_prefix='/home') app.register_blueprint(crn.crnbp, url_prefix='/crn') # @app.route('/') # def root(): # return redirect(url_for('binterface.ctl_jobs', filter='php_only')) @app.after_request def session_commit(response): session = getattr(g, 'session', None) if session is not None: g.session.commit() return response @app.before_request def before_request(): g.session = Session() @app.teardown_request def teardown_request(exception): session = getattr(g, 'session', None) if session is not None: session.close() return app
from flask import Flask, jsonify, request app = Flask(__name__) app.id_count = 1 app.users = {} @app.route("/ping", methods=['get']) def ping(): return "pong" @app.route("/sign-up", methods=['POST']) def sign_up(): new_user = request.json new_user["id"] = app.id_count app.users[app.id_count] = new_user app.id_count = app.id_count + 1 return jsonify(new_user)
from flask import Flask, request, jsonify app = Flask(__name__) app.users = {} # 가입한 사용자 저장 key = id: int, value = new_user: JSON app.id_count = 1 @app.route("/ping", methods=['GET']) def ping() -> str: return "pong" # 회원가입 @app.route("/sign-up", methods=['POST']) def sign_up(): new_user = request.json # JSON -> dict new_user["id"] = app.id_count app.users[app.id_count] = new_user app.id_count = app.id_count + 1 return jsonify(new_user) # dict -> JSON # 트윗 구현 app.tweets = [] @app.route('/tweet', methods=['POST']) def tweet() -> tuple: payload = request.json user_id = int(payload["id"]) tweet = payload["tweet"]
def getrandbytes(k): ''' get an ascii string of randbits ''' bits = getrandbits(k * 8) hex_bits = hex(bits)[2:].strip('L') if len(hex_bits) % 2 == 1: hex_bits = '0' + hex_bits return unhexlify(hex_bits) ############################### # TOQU: save this stuff to a DB app.users = {} try: with open('users.json') as users_jsonfile: app.users = json.loads(users_jsonfile.read()) except IOError: pass except ValueError: pass ############################### def hash_password(salt, password): ''' salt and hash the password ''' saltpass = "".join([chr(ord(c)) for c in salt] +
def index(): name = "" if current_user.is_anonymous else current_user.get_username() user_list = [t[0] for t in va_query(db_name, "select username from user")] return render_template('index.html', user_list=user_list, logging=not current_user.is_anonymous, name=name) @app.route('/test') def test(): return render_template('t.html') if __name__ == '__main__': app.users = users from views.login import login_pages, login_manager app.register_blueprint(login_pages) login_manager.login_view = 'login_pages.login' login_manager.init_app(app) from views.editor import editor_pages app.register_blueprint(editor_pages) from views.config import config_pages app.register_blueprint(config_pages) from views.blog import blog_pages app.register_blueprint(blog_pages)
#!/usr/bin/python3 import json from flask import Flask, request, make_response, jsonify from models import Users, User, Game, LoginException app = Flask(__name__) # Arseny: using global conditions like `users` and variables like `game` # Arseny: is a bad software design pattern. Using global variables like # Arseny: `game` is really bad. It's not solution is not scalable. # Arseny: What to use instead of this? For example try create new class # Arseny: Which inherit `Flask`. Add to this properties for `users` and # Arseny: `game` app.users = Users() app.game = None @app.route('/') def index(): return 'Hello world' @app.route('/login', methods=['POST']) def login(): try: user = User(request.json['login']) app.users.add_user(user) except LoginException as err: return make_response(jsonify(status=err.message), 400) print(app.users)
clear_old_delays() app.day = str(t.tm_year) + str(t.tm_yday) return payments @app.route("/getresults", methods=['POST']) def send_results(): user = request.form['username'] results = calculate_results(app.users, app.groups[app.users[user][1]], 10) for ower, payment in results.items(): app.ledger[ower].append(payment) return (str(app.ledger[user]) if app.ledger[user] else "you get paid") + "\n" if __name__ == "__main__": os.environ['TZ'] = 'US/Eastern' app.groups = {} app.users = {} # map from username to (list of delays) app.ledger = {} app.alarms = defaultdict(list) # map from username to alarms for the user t = time.localtime() app.day = str(t.tm_year) + str(t.tm_yday - 1) if len(sys.argv) == 2: CONSUMER_ID = ANDREW_CONSUMER_ID CONSUMER_SECRET = ANDREW_CONSUMER_SECRET APP_SECRET = ANDREW_APP_SECRET p = 8081 else: p = 8080 app.secret_key = APP_SECRET app.delays = {} app.successes = {}
jwtPassword = '******' APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads') app.upload_path = Path(os.path.join(APP_ROOT, './static/uploads')) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config.update( dict( #SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Lax', SESSION_TYPE='redis')) cwd = os.path.dirname(os.path.realpath(__file__)) with open('data.json') as jdata: data = json.load(jdata) app.users = data['users'] def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if 'profile' not in session: return redirect('/') return f(*args, **kwargs) return decorated #def login_required(jdata): # @wraps(jdata) # def wrapper(*args, **kwargs):
from flask import Flask, jsonify, request from flask.json import JSONEncoder app = Flask(__name__) app.users = {} # 새로 가입한 사용자 users란 변수에 정의 한다. app.id_count = 1 # 회원 가입하는 사용자의 id 값을 저장 app.tweets = [] class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) return JSONEncoder.default(self, obj) app.json_encoder = CustomJSONEncoder @app.route("/ping", methods=['GET']) def ping(): return "pong" @app.route("/sign-up", methods=['POST']) def sign_up(): new_user = request.json # json -> dictionary new_user["id"] = app.id_count app.users[app.id_count] = new_user app.id_count = app.id_count + 1
def create_app(): app = Flask(__name__, static_folder='static') CORS(app) app.register_blueprint(v1.bp, url_prefix='/v1') app.users = [] return app
import cPickle as pickle import pusher import sys app = Flask(__name__) app.rooms = {} app.default_matrix = [ {"sample": "kick", "path": "/static/samples/kick.mp3", "melodic": False, "triggers": [True, False, False, False, True, False, False, False, True, False, False, False, True, False, False, False]}, {"sample": "hat", "path": "/static/samples/hat.mp3", "melodic": False, "triggers": [False, False, True, False, False, False, True, False, False, False, True, False, False, False, True, False]}, {"sample": "snare", "path": "/static/samples/snare.mp3", "melodic": False, "triggers": [False, False, False, False, True, False, False, False, False, False, False, False, True, False, False, False]}, {"sample": "crash" ,"path": "/static/samples/crash.mp3", "melodic": False, "triggers": [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]}, {"sample": "bass", "path": "/static/samples/bass.mp3", "melodic": True, "triggers": [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False], "notes": ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], "editing": True} ] app.users = {} def randomRoomName(): return "%s%d" % (random.choice(app.words), random.randint(1, 99)) def persist(): pickle.dump(app.rooms, open("db", "w")) app.persist_timer = threading.Timer(5.0, persist) app.persist_timer.start() @app.route("/change/<room>/<sample>/<position>", methods=['POST', 'DELETE']) def change(room, sample, position): enabled = request.method == 'POST' for track in app.rooms[room]: if track["sample"] == sample:
from flask import Flask from flask import request from flask_cors import CORS import json user1 = User('358480786506', {'lat': 60.17072, 'lon': 24.943043}) USERS = {'358480786506': user1} for user in USERS.values(): user.start() app = Flask(__name__) CORS(app) app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' app.users = USERS # Requests from ngrok @app.route('/nokia', methods=['POST']) def update_reachable(): event_info = read_nokia_response() event_type = parse_call_event(event_info) print(event_type) return "OK" def read_nokia_response(): info_str = request.data.decode('utf-8')
def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: return redirect(url_for('login', next=request.url)) return f(*args, **kwargs) return decorated_function app = Flask(__name__) app.iniconfig = FlaskIni() with app.app_context(): app.iniconfig.read('./configs/config.ini') app.secret_key = app.iniconfig['FLASK']['APP_SECRET_KEY'] app.users = utils.load_users(app.iniconfig['FLASK']['USER_FILE']) app.youtube_obj, app.spotify_obj = None, None @app.before_request def before_request(): # Setup user if session.get('logged_in', None): g.user = { 'username': session['username'], 'secret_key': session['secret_key'] } else: g.user = None # Setup query objects