def load_whitelist(whitelist_file): """Load whitelist from file to database.""" whitelist_user_ids = set() for line in whitelist_file: data: str = line.strip() if len(data) == 0: continue if data[0] == '#': continue whitelist_user_ids.add(int(data)) models.db_init(botsettings.database_url) with models.db_proxy.transaction(): existing_whitelist_users = models.User.select().where( models.User.user_id << whitelist_user_ids) models.User.update(is_whitelisted=True).where( models.User.user_id << whitelist_user_ids).execute() new_whitelist_user_ids = whitelist_user_ids - \ {x.user_id for x in existing_whitelist_users} if len(new_whitelist_user_ids) > 0: models.User.bulk_create([ models.User(user_id=user_id, chat_id=None, username=None, is_whitelisted=True) for user_id in new_whitelist_user_ids ])
def app_conf(): "init db and return app_conf" m_conf = g.conf.mconfig['contact'] db_path = os.path.join(g.conf._basedir, m_conf['db_path']) db = SqliteDatabase(db_path, **g.conf.DATABASE_CONNECT_OPTIONS) # proxy to db db_proxy.initialize(db) if not os.path.exists(db_path): db_init(db, m_conf) return m_conf
def deop_username(username): """Make user with given username admin.""" models.db_init(botsettings.database_url) with models.db_proxy.transaction(): try: user = models.User.get(username=username) user.is_admin = False user.save() logger.info('Successfully deopped user {}'.format(username)) except models.User.DoesNotExist: logger.warning('User {} not found in database'.format(username))
def setup_app(): #Add templates path -- more to come? bottle.TEMPLATE_PATH.insert(0, path.join(config.BASE_DIR, 'templates')) bottle.debug(True) models.db_init() #Change errors to warnings warnings.simplefilter('error') #Grab the app app = bottle.app() app.catchall = False sess_app = SessionMiddleware(app, config.SESSION_OPTS) sess_app = DebuggedApplication(sess_app, evalex=True) return sess_app
#import json #import pprint import os from werkzeug.exceptions import default_exceptions from flask import redirect, render_template, request, session #from flask_session import Session from models import Users, Recipes, db_init from utils import app from helpers import login_required, apology # init and fulfill the db # 'allergies.json' - allergy's type and common products containing the allergen # 'full_format_recipes.json' - recipes collection from kaggle basepath = os.path.abspath(".") db_init(basepath + '/static/allergies.json', basepath + '/static/full_format_recipes.json') @app.route("/login", methods=["GET", "POST"]) def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403)
else: session.pop('username', None) # Return response utls.display_tables() return 204 api.add_resource(AdmnQuizzesAPI, '/admin/quizzes') api.add_resource(AdmnQuizAPI, '/admin/quizzes/<int:qzid>') api.add_resource(AdmnQuestionsAPI, '/admin/quizzes/<int:qzid>/questions') api.add_resource(AdmnQuestionAPI, '/admin/quizzes/<int:qzid>/questions/<int:qid>') api.add_resource(UsrQuizzesAPI, '/user/quizzes') api.add_resource(UsrQuizAPI, '/user/quizzes/<int:qzid>') api.add_resource(UsrQuizRtAPI, '/user/quizzes/<int:qzid>/result') api.add_resource(UsrQuestionAPI, '/user/quizzes/<int:qzid>/questions/<int:qid>') api.add_resource(UsersAPI, '/users') api.add_resource(SessionAPI, '/session') if __name__ == '__main__': #Initial config for db, this can be disabled models.db_init() utls.display_tables() app.debug = True app.run('192.168.33.10', 5001)
logs.debug_ ("SessionAPI del fn: %s" %(request.url)) # Pop user from session userid, username = utls.get_user_from_hdr() if 'username' not in session: logs.debug_("User already not in session") else: session.pop('username', None) # Return response utls.display_tables() return 204 api.add_resource(UserIdeasAPI, '/user/ideas') api.add_resource(UserIdeaAPI, '/user/ideas/<int:ideaid>') api.add_resource(UsersAPI, '/users') api.add_resource(SessionAPI, '/session') if __name__ == '__main__': #Initial config for db, this can be disabled models.db_init() utls.display_tables() app.debug = True app.run('127.0.0.1', 5004)
try: import eventlet eventlet.monkey_patch() print('Using eventlet') create_thread_func = lambda f: f start_thread_func = lambda f: eventlet.spawn(f) except ImportError: try: import gevent import gevent.monkey gevent.monkey.patch_all() print('Using gevent') create_thread_func = lambda f: gevent.Greenlet(f) start_thread_func = lambda t: t.start() except ImportError: import threading print('Using threading') create_thread_func = lambda f: threading.Thread(target=f) start_thread_func = lambda t: t.start() from app import socketio, app from config import DEBUG from models import db_init db_init() socketio.run(app, debug=DEBUG)
import logging from logging import Formatter, FileHandler from flask_wtf import Form from forms import * from models import db_init, Venue, Artist, Show from datetime import datetime import data_dict #----------------------------------------------------------------------------# # App Config. #----------------------------------------------------------------------------# app = Flask(__name__) moment = Moment(app) # TODO: [COMPLETED] connect to a local postgresql database db = db_init(app) #----------------------------------------------------------------------------# # Filters. #----------------------------------------------------------------------------# def format_datetime(value, format='medium'): date = dateutil.parser.parse(value) if format == 'full': format="EEEE MMMM, d, y 'at' h:mma" elif format == 'medium': format="EE MM, dd, y h:mma" return babel.dates.format_datetime(date, format) app.jinja_env.filters['datetime'] = format_datetime
import json,os,sys from flask import g from models import db_proxy,Job,Job_type,Ip,Mail,db_init from datetime import datetime from peewee import SqliteDatabase from jinja2 import Environment, FileSystemLoader sys.path.append(os.path.dirname(os.path.dirname(__file__))) from share_util import guid, mail_handler from app import sys_conf app_conf = sys_conf.mconfig['jobs'] db_path = os.path.join(sys_conf._basedir,app_conf['db_path']) db = SqliteDatabase(db_path, **sys_conf.DATABASE_CONNECT_OPTIONS) db_proxy.initialize(db) if not os.path.exists(db_path): db_init(db,app_conf) # import job_types sys.path.append(app_conf.get('mod_path',os.path.join(os.path.dirname(__file__),'mod_tools'))) import job_types class job_handler(): """offer a interface to treat web job """ def __init__(self): self.version = 'test' def create_job(self,req): "create job by input request" t_guid = req.form.get('guid','') if t_guid:
from flask import Flask, render_template, request, flash, Response, redirect from models import Pic, db_init, db from werkzeug.utils import secure_filename import base64 app = Flask(__name__) app.secret_key = b'=N1B8-+ydFaEJ' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///images.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db_init(app) @app.route("/") def index(): return render_template("index.html") @app.route("/upload", methods=['POST']) def upload(): pic = request.files['pic'] if not pic: return "Image not uploaded" filename = secure_filename(pic.filename) mimetype = pic.mimetype img_string = base64.b64encode(pic.read()) img = Pic(img=img_string, mimetype=mimetype, name=filename) db.session.add(img) db.session.commit()
""" logger.info('Loading contact list...') with open(contactlist_filename, encoding='utf-8') \ as contactlist_file: return contactlist_file.read() logger.info('Starting bot...') message_help: str = get_help(help_file) logger.info('Help message:\n' + message_help) message_contact_list: str = get_contactlist(contactlist_file) logger.info('Contact list:\n' + message_contact_list) models.db_init(database_url) logger.info('Token loaded') logger.info('Proxy data loaded') if proxy_data is not None: telebot.apihelper.proxy = {proxy_data[0]: proxy_data[1]} bot: telebot.TeleBot = telebot.TeleBot(token, num_threads=thread_number) logger.info('Bot instance created') def get_error_message(exception, if_ok: Optional[str] = None) -> str: """ Return error message based on exception `exception`.