def main(): args = docopt(__doc__, options_first=True) if args["<command>"] == "syncdb": init_db() else: exit("%r is not a manage.py command. See 'manage.py help'." % args["<command>"])
def test_main(self): """Test the high level environment initialization logic.""" self.mox.StubOutWithMock(initalize_environment, 'create_user') self.mox.StubOutWithMock(initalize_environment, 'create_db_engine') self.mox.StubOutWithMock(initalize_environment, 'get_env_config') self.mox.StubOutWithMock(initalize_environment, 'create_db') self.mox.StubOutWithMock(initalize_environment, 'create_db_lang') self.mox.StubOutWithMock(initalize_environment, 'install_postgis') self.mox.StubOutWithMock(database, 'init_db') mock_connection = MockDBConnection() mock_engine = MockEngine(mock_connection) initalize_environment.create_user(DATABASE_USER, DATABASE_PASSWORD).AndReturn(None) initalize_environment.create_db_engine(DATABASE_USER, DATABASE_PASSWORD).AndReturn(mock_engine) initalize_environment.get_env_config().AndReturn(TEST_CONFIG_SETTINGS) initalize_environment.create_db(mock_connection, DATABASE_NAME).AndReturn(None) initalize_environment.create_db_lang(DATABASE_NAME).AndReturn(None) initalize_environment.install_postgis(DATABASE_NAME).AndReturn(None) database.init_db().AndReturn(mock_connection) self.mox.ReplayAll() initalize_environment.main(DATABASE_TYPE)
def join(): print "join" if request.method =='POST': print "method is post" nick = request.form["nick"].strip() emailaddr = request.form["emailaddr"].strip() password = request.form["password"].strip() init_db() targer_user = User.query.filter_by(email=emailaddr).first() if not (targer_user == None): flash('Email is invalid or already taken') return redirect(url_for('join')) if (targer_user == None): """insert""" new_user = User(emailaddr,password,nick) db_session.add(new_user) db_session.commit() db_session.close() return redirect(url_for('login')) else: print "method is get" return render_template('signup_form.html')
def main(): if not os.path.exists(database.DB_FILE): print "Initializing database '%s'..." % database.DB_FILE database.init_db() print "Loading data file '%s'..." % DATA_FILE with open(DATA_FILE, "r") as f: data = json.load(f) all_cards = [] for key in data: set_cards = data[key]["cards"] for card in set_cards: card["set"] = data[key]["name"] all_cards += set_cards all_formatted_cards = [] print "Formatting card entries..." for card in all_cards: all_formatted_cards.append(db_format(card)) print "Inserting %d cards into the database..." % len(all_formatted_cards) database.add_reference_cards(all_formatted_cards) print "Done"
def download_pageviews(backend): ''' New URL: http://dumps.wikimedia.org/other/pagecounts-raw/2011/2011-12/ Complele URL: http://dumps.wikimedia.org/other/pagecounts-raw/2011/2011-12/pagecounts-20111201-000000.gz ''' today = datetime.datetime.today() month = '0%s' % today.month if len(str(today.month)) == 1 else today.month url = '%s/%s/%s-%s/' % ('http://dumps.wikimedia.org/other/pagecounts-raw', today.year, today.year, month,) print url text = urllib2.urlopen(url).read() urls = re.findall('a href\="pagecounts\-(.*?)\.gz"', text) files = dict((generate_key(url, '%s%s.gz' % ('pagecounts-', u)), '%s%s%s.gz' % (url, 'pagecounts-', u)) for u in urls) fetched =[] db_meta = init_db(backend, 'meta', 'wikistats') db_pageviews = init_db(backend, 'pageviews', 'wikistats') for filename in files: res = db_meta.fetch(ks='meta', key=filename) if not res: fetched.append(files[filename]) # if settings.DEBUG: # fetched = fetched[0:1] for remote_file in fetched: print 'Downloading %s' % remote_file success = fetchdata(db_pageviews, remote_file, today, backend) print success if success: print 'Yes, i am going to store %s' % remote_file db_meta.store(ks='meta', key=remote_file, columns={'downloaded':1})
def testMultiPlayerMatch(self): init_db() player_one = Player(owner=1, desc="I'm uniq", enabled=True) db_session.add(player_one) db_session.commit() print "player_one.id:", player_one.id player_two = Player(owner=2, desc="I'm not", enabled=True) db_session.add(player_two) db_session.commit() print "player_two.id:", player_two.id match = Match(players=[player_one, player_two]) db_session.add(match) assert match.state == 'unplayed' print "Match before commit: %s"%(match,) db_session.add(match) db_session.commit() match_persist = db_session.query(Match).first() print "Match re-read: %s"%(match_persist,) assert match_persist.playerresults[0].result == 0 assert match_persist.playerresults[0].player.owner == 1 assert match_persist.playerresults[0].player.desc == "I'm uniq" assert match_persist.playerresults[0].player.enabled == True assert match_persist.playerresults[1].result == 0 assert match_persist.playerresults[1].player.owner == 2 assert match_persist.playerresults[1].player.desc == "I'm not" assert match_persist.playerresults[1].player.enabled == True reset_db()
def setup(env): app.config.from_pyfile("config/%s.py" % env) init_engine(app.config["DATABASE_URI"]) init_db() return app
def setup(): init_db() con = engine.connect() con.execute(users.delete()) con.execute(users.insert(), name='admin', email='admin@localhost', password='******') con.execute(users.insert(), name='anna', email='anna@localhost', password='******') return "ok"
def init(): messages = [] # init database init_db() # this operation won't create tables if they exist # add init data for databases users = User.query.filter(User.name == "admin").all() if len(users) == 0: u1 = User(name='admin', email='*****@*****.**', password='******') db_session.add(u1) db_session.commit() messages.append("user 'admin' added!") else: messages.append("valid user exists, skip user init.") # init upload folder ==> moved to action_hooks/build # if not os.path.exists(current_app.config['UPLOAD_FOLDER']): # os.mkdir(current_app.config['UPLOAD_FOLDER']) # messages.append("upload folder created!") # else: # messages.append("upload folder existed!") for message in messages: flash(message) return render_template('admin/init.html')
def main(database_type): """Driver for this CLI utility. @param database_type: The name of the type of database to initialize. Typical values include development or test. @type database_type: str """ env_config = get_env_config() if not is_valid_database_type(database_type, env_config): display_invalid_type_message(database_type, env_config) return db_init_config = env_config[CONFIG_DATABASE_INFO_KEY][database_type] user = db_init_config['user'] password = db_init_config['pass'] database_name = db_init_config['db'] create_user(user, password) engine = create_db_engine(user, password) connection = engine.connect() create_db(connection, database_name) create_db_lang(database_name) install_postgis(database_name) database.init_db() connection.close()
def test_init_db(self): #when init_db(self.dbname) self.db = connect_db(self.dbname) #expect self.assertEqual(self.db.execute('select * from user').fetchall(), []) self.assertEqual(self.db.execute('select * from entry').fetchall(), [])
def db(test_app, request): """initialize database schema and drop when finished""" init_db() def cleanup(): clear_db() request.addfinalizer(cleanup)
def setup(env): app.config.from_pyfile('config/%s.py' % env) app.config.from_pyfile('config/%s_secret.py' % env, silent=True) init_engine(app.config['DATABASE_URI']) init_db() return app
def init_or_flush_cards(): ''' Creates tables and clears them ''' init_db() for database in [UserHand, ComputerHand, Deck]: database.query.delete() save()
def testCreateTrivialMatch(self): init_db() match = Match() assert match.state == 'unplayed' db_session.add(match) db_session.commit() match_persist = db_session.query(Match).first() assert match_persist.state == 'unplayed' reset_db()
def setup(conf_path): global app, games app.config.from_pyfile(conf_path) init_engine(app.config['DATABASE_URI']) init_db() with open('config/games.json') as data_file: games = json.load(data_file) return app
def initdb(): init_db() res = [] data = db.session.query(Reservation) for item in data.all(): res.append(item.asList()) return render_template('output.html', reservationList = res)
def setUp(self): # This should be sufficient init_db() base_url = "http://namuu/" self.mms = RDBMSMediaAndMetaStorage(base_url) self.us = UserStorage(base_url) # But this is actually rquired self.mms.clean() self.assumeNoKeys()
def __init__(self): """ Constructor.""" init_db() c = config.Config() self.config = c.cfg if os.getenv('HEROKU') is None: logging.basicConfig(filename=self.config.get('salvavida', 'logfile'), level=logging.DEBUG) self.feed_tags = self.config.get('twitter', 'feed_tags') self.reply_tags = self.config.get('twitter', 'reply_tags') self.filter_tags = self.config.get('twitter', 'filter_tags')
def run(debug=False, **kw): import app app_instance = app.create_app() app.connect_all(app_instance) # Create the sqlite database if it doesn't exist. if debug and not os.path.exists(config.SQLITE_DB_FILE): import database database.init_db() app_instance.run(debug=debug, **kw)
def initdb(): """Initialize the database.""" # try connect to db # show its structure #else init_db() print '-'*10 print 'Initializing db at '+ DB_URL return
def __init__(self): #check if db exists if not database_exists(DB_URL): print '-'*10 print 'Initializing db at '+ DB_URL init_db() print 'successfull' print '-'*10 self.db_session = db_session super(Ming, self).__init__()
def first_data(user_manager): init_db() user1 = User(username='******', email='*****@*****.**', active=True, password=user_manager.hash_password('admin')) user2 = User(username='******', email='*****@*****.**', active=True, password=user_manager.hash_password('user')) role_user = Role(name='user') user1.roles.append(Role(name='admin')) user1.roles.append(role_user) user2.roles.append(role_user) db_session.add(user1) db_session.add(user2) db_session.commit()
def create_app(config=None, app_name=None, blueprints=None): if app_name is None: app_name = DEFAULT_APP_NAME app = Flask(app_name) CORS(app) app.register_blueprint(api) configure_app(app, config) init_db() return app
def create_app(db_url): """This is a test :param db_url: connection url to the database being used :returns: the initialized and created app instance """ app = Flask(__name__) (app.db_session, app.db_metadata, app.db_engine) = init_db(db_url) @app.teardown_request def shutdown_session(exception=None): app.db_session.remove() create_api(app, API_VERSION) # support for remote debugging in Intellij and pycharm # # Set IDEA_ORGANISATIONS_REMOTE_DEBUG_ON to True in your environment # prior to starting the application to get remote debugging. # # Set IDEA_REMOTE_DEBUG_SERVER to the ip/hostname of the machine running the # debug server. # # Set IDEA_ORGANISATIONS_REMOTE_DEBUG_SERVER to the port of the debug server prosess # # For the remote debugging to work you will also have to make sure # the pycharm-debug.egg is on your path (check your environment file). if os.environ.get('IDEA_ORGANISATIONS_REMOTE_DEBUG_ON') == 'True': server = os.environ.get('IDEA_REMOTE_DEBUG_SERVER') port = os.environ.get('IDEA_ORGANISATIONS_REMOTE_DEBUG_PORT') app.logger.info("Idea remote debugging is on! Will connect to debug server running on %s:%s" % (server, port)) import pydevd pydevd.settrace(server, port=int(port), stdoutToServer=True, stderrToServer=True) return app
def __init__(self): """ Constructor.""" init_db() c = config.Config() self.config = c.cfg logging.basicConfig(filename=self.config.get('salvavida', 'logfile'), level=logging.DEBUG) self.stdin_path = '/dev/null' self.stdout_path = self.config.get('salvavida', 'logfile') self.stderr_path = self.config.get('salvavida', 'errfile') self.pidfile_path = self.config.get('salvavida', 'pidfile') self.pidfile_timeout = 5 self.feed_tags = self.config.get('twitter', 'feed_tags') self.reply_tags = self.config.get('twitter', 'reply_tags') self.filter_tags = self.config.get('twitter', 'filter_tags')
def prepare_db(backend): if backend=='mongo': db = init_db(backend, 'wikistats', 'pageviews') coll = db.get_collection('pageviews') coll.ensure_index('hash') coll.ensure_index('total') coll.ensure_index('total30')
def make_new_gye(): if request.method =='GET': return render_template("make_new_gye.html") elif request.method =='POST': init_db() new_gye = Gye() new_gye.gname=request.form["gname"].strip() new_gye.gintro=request.form["gintro"].strip() new_gye.gfounder=session['email'] new_gye.gmemcnt=0 db_session.add(new_gye) db_session.commit() db_session.close() return render_template("make_new_gye.html")
def init(): if not os.path.exists('db'): os.makedirs('db') init_db() print("Createing the a test category..") category_controller.create(name="Test") print("Creating a test slide..") slide_controller.create( title="test title", screenshot="img/badge-reserved.jpg", description="test desc", url="https://github.com/moztn/firefoxOSAppDay-Slides", category=1 ) print("Fixtures created successfully")
def create_app(db_url): app = Flask(__name__) (app.db_session, app.db_metadata, app.db_engine) = init_db(db_url) app.debug = os.environ.get('DEBUG') == 'True' _paragraph_re = re.compile(r'(?:\r\n|\r|\n){1,}') @app.teardown_request def shutdown_session(exception=None): app.db_session.remove() @app.template_filter('strftime') def _jinja2_filter_datetime(date, in_format='%Y-%m-%d', out_format='%d-%m-%Y'): if date: date = datetime.datetime.strptime(date, in_format) return date.strftime(out_format) @app.template_filter('nl2br') def _nl2br(value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') \ for p in _paragraph_re.split(escape(value))) result = Markup(result) return result @app.template_filter('sort_vedtak') def _jinja2_filter_sort_vedtak(vedtak): if len(vedtak) == 0: return [] else: id_sorted = sorted(vedtak, key=id) s = sorted(id_sorted, reverse=True, key=lambda v: v.get('vedtaksdato') if v.get('vedtaksdato') else datetime.datetime.now().isoformat()) return s create_api(app, API_VERSION) create_bouncer(app) # support for remote debugging in Intellij and pycharm # # Set IDEA_SAK_REMOTE_DEBUG_ON to True in your environment # prior to starting the application to get remote debugging. # # Set IDEA_REMOTE_DEBUG_SERVER to the ip/hostname of the machine running the # debug server. # # Set IDEA_SAK_REMOTE_DEBUG_SERVER to the port of the debug server prosess # # For the remote debugging to work you will also have to make sure # the pycharm-debug.egg is on your path (check your environment file). if os.environ.get('IDEA_SAK_REMOTE_DEBUG_ON') == 'True': server = os.environ.get('IDEA_REMOTE_DEBUG_SERVER') port = os.environ.get('IDEA_SAK_REMOTE_DEBUG_PORT') app.logger.info("Idea remote debugging is on! Will connect to debug server running on %s:%s" % (server, port)) import pydevd pydevd.settrace(server, port=int(port), suspend=False, stdoutToServer = True, stderrToServer = True) return app
def main(): #Build the Argument parser parser = argparse.ArgumentParser(description='Generates attack graph input files from topological files') parser.add_argument('--hosts-interfaces-file', dest='hosts_interfaces_file', required=True, help='The CSV file containing the hosts and the interfaces.') parser.add_argument('--vlans-file', dest='vlans_file', required=True, help='The CSV file containing the VLANS.') parser.add_argument('--vulnerability-scan', dest='vulnerability_scan', required=False, nargs='+', help='The Nessus scanner report file(s).') parser.add_argument('--flow-matrix-file', dest='flow_matrix_file', required=False, help='The CSV file containing the flow matrix') parser.add_argument('--routing-file', dest='routing_file', required=False, help='The CSV file containing the routing informations') parser.add_argument('--mulval-output-file', dest='mulval_output_file', required=False, help='The output path where the mulval input file will be stored.') parser.add_argument('--attackerlocation', dest='attackerlocation', required=False, help='The file containing attacker location name') parser.add_argument('--to-fiware-xml-topology', dest='to_fiware_xml_topology', required=False, help='The path where the XML topology file should be stored.') parser.add_argument('--display-infos', action='store_true', dest='display_infos', required=False, help='Display information and statistics about the topology.') parser.add_argument('-v', dest='verbose', action='store_true', default=False, help='Set log printing level to INFO') parser.add_argument('-vv', dest='very_verbose', action='store_true', default=False, help='Set log printing level to DEBUG') args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) if args.very_verbose: logging.basicConfig(level=logging.DEBUG) if not args.verbose and not args.very_verbose: logging.basicConfig(level=logging.WARNING) logging.info("Loading the vulnerability database connector.") init_db() topology = Topology() topology.load_from_topological_input_files(args.hosts_interfaces_file, args.vlans_file) if args.vulnerability_scan: for vulnerabity_scan_file in args.vulnerability_scan: topology.add_nessus_report_information(vulnerabity_scan_file) if args.flow_matrix_file: topology.flow_matrix = FlowMatrix(topology, args.flow_matrix_file) if args.routing_file: topology.load_routing_file(args.routing_file) else: logging.info("No flow matrix file has been provided.") topology.flow_matrix = FlowMatrix(topology) if args.display_infos: topology.print_details() if args.mulval_output_file: topology.to_mulval_input_file(args.mulval_output_file , args.attackerlocation) if args.to_fiware_xml_topology: topology.to_fiware_topology_file(args.to_fiware_xml_topology)
def insertComponent(componentRow): init_db() component = componentRow db_session.add(component) db_session.commit()
import logging import os import connexion from database import init_db, User, Track, Playlist from sqlalchemy import desc from hashlib import md5 from flask import jsonify from flask_cors import CORS db_session = init_db() session = {} def logout(): session.clear() def login(email, password): user = db_session.query(User).filter(User.email == email).filter( User.password == md5(str.encode(password)).hexdigest()).first() if user: session['id'] = user.id return jsonify(user.to_json()) def register(name, email, password): user = User(name=name, email=email, password=md5(str.encode(password)).hexdigest()) db_session.add(user)
# this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) logger = logging.getLogger("alembic.env") custom_arguments = context.get_x_argument(as_dictionary=True) app_config = get_config(override=custom_arguments, prompt_db_creds=True) # noinspection PyUnresolvedReferences from {{ cookiecutter.module_name }} import models, database database.init_db() database_urls = {"main": app_config["database_url"]} target_metadata = {"main": database.Base.metadata} def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
import os from database import init_db from git_helper import init_gitServer os.system("rm database.db") print "[+] Init Database" init_db() print "[+] Init Git Server" init_gitServer()
def initialize(): """Init function for this module""" with INIT_LOCK: global __INITIALIZED__, app, FULL_PATH, RUNDIR, ARGS, DAEMON, PIDFILE, VERBOSE, LOG_FILE, LOG_DIR, logger, PORT, SERVER, DATABASE, AUTH, \ CURRENT_COMMIT, LATEST_COMMIT, COMMITS_BEHIND, COMMITS_COMPARE_URL, USE_GIT, WEBROOT, HOST, KIOSK, DATA_DIR, THREADS if __INITIALIZED__: return False # Set up logger if not LOG_FILE: LOG_FILE = os.path.join(DATA_DIR, 'logs', 'maraschino.log') FILENAME = os.path.basename(LOG_FILE) LOG_DIR = LOG_FILE[:-len(FILENAME)] if not os.path.exists(LOG_DIR): try: os.makedirs(LOG_DIR) except OSError: if VERBOSE: print 'Unable to create the log directory.' logger = maraschinoLogger(LOG_FILE, VERBOSE) # check if database exists or create it from database import init_db if KIOSK: logger.log('Running in KIOSK Mode, settings disabled.', 'INFO') try: logger.log('Opening database at: %s' % (DATABASE), 'INFO') open(DATABASE) except IOError: logger.log('Opening database failed', 'CRITICAL') try: logger.log('Checking if PATH exists: %s' % (DATABASE), 'WARNING') dbpath = os.path.dirname(DATABASE) if not os.path.exists(dbpath): try: logger.log('It does not exist, creating it...', 'WARNING') os.makedirs(dbpath) except: logger.log('Could not create %s.' % (DATABASE), 'CRITICAL') print 'Could not create %s.' % (DATABASE) quit() except: logger.log('Could not create %s.' % (DATABASE), 'CRITICAL') quit() logger.log('Database successfully initialised', 'INFO') init_db() # Web server settings from tools import get_setting_value if get_setting_value('maraschino_port'): port_arg = False for arg in ARGS: if arg == '--port' or arg == '-p': port_arg = True if not port_arg: PORT = int(get_setting_value('maraschino_port')) # Set up AUTH username = get_setting_value('maraschino_username') password = get_setting_value('maraschino_password') if username and password != None: AUTH = {'username': username, 'password': password} # Set up web server if '--webroot' not in str(ARGS): WEBROOT = get_setting_value('maraschino_webroot') if WEBROOT is None: WEBROOT = '' if WEBROOT: if WEBROOT[0] != '/': WEBROOT = '/' + WEBROOT d = wsgiserver.WSGIPathInfoDispatcher({WEBROOT: app}) else: d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) SERVER = wsgiserver.CherryPyWSGIServer((HOST, PORT), d) __INITIALIZED__ = True return True
def db_session(): with tempfile.NamedTemporaryFile() as temp_db: yield init_db(temp_db.name)
def connect_db(): init_db()
# author = [email protected] from flask import Flask, request, Response, abort from sqlalchemy import __version__, and_, exc import database from models import Product, User application = app = Flask(__name__) db_instance = database.init_db() print("SQLAlchemy version: " + __version__) # gets products from the database that belong to a certain user. If no products found it returns 404 (Not Found) def get_products(user_id): all_products = [] exists = False for instance in db_instance.query(Product).filter( Product.user_id == user_id): exists = True all_products.append(instance.__repr__()) if exists: string = "[ " + " , ".join(all_products) + " ]" return Response(string, mimetype='application/json', headers={ 'Cache-Control': 'no-cache', 'Access-Control-Allow-Origin': '*' })
from flask import Flask from v1.api import api_v1 from database import init_db from v1.models import Base from storage import SQLStorage import logging logging.basicConfig(level=logging.INFO) # flask boiler plate init code app = Flask(__name__) app.config['SECRET_KEY'] = b'_5#y2L"F4Q8z\n\xec]/' app.config.from_object(os.environ.get('APP_ENV_CONFIG')) db_session = init_db(app, Base) app.config['db_session'] = db_session app.config['storage'] = SQLStorage(db_session) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() # register blueprints here app.register_blueprint(api_v1, url_prefix='/v1') #DEVELOPMENT TIME if __name__ == '__main__': print('Flask app running fro main ....')
def main(): init_db() session = Session() session.commit()
def main(): init_db() merge_fake_data() app.run()
from slpp import slpp as lua from data_read import read_kill_events, read_kill_event_count, read_position_event_count, read_sources, read_realms, read_position_events from database import db, init_db from ingest_kills import ingest_kill_data from ingest_position import ingest_position_data # Uncomment for SQL Logging # import logging # logging.basicConfig() # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) app = Flask(__name__, static_folder='../website', static_url_path='') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False init_db(app) db.init_app(app) @app.route('/api/kill-events') def get_kill_events(): map_id = request.args.get('mapId') is_instance = request.args.get('isInstance') source_player_id = request.args.get('sourcePlayerId') event_limit = int(request.args.get('eventLimit')) is_instance = True if is_instance == 'true' else False return jsonify( read_kill_events(map_id, is_instance, source_player_id, event_limit))
def create_user(): init_db()
from __future__ import with_statement from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relation, backref from database import Show, Episode, init_db import codecs import re import sqlalchemy session = init_db(transactional=True) def import_data(filename): """Import episode names and ratings from a file.""" regex = re.compile(""""(?P<show_name>.*?)"\s+\((?P<year>\d+)(?:|/.*?)\)\s+\{(?P<episode_name>.*?)\s?\(\#(?P<season_no>\d+)\.(?P<episode_no>\d+)\)\}""") with codecs.open(filename, "r", "latin-1") as ratings: # Generate all the lines that matched. matches = (match for match in (regex.search(line.strip()) for line in ratings) if match) counter = 0 for match in matches: counter += 1 if not counter % 100: print counter episode = {} for field in ["show_name", "year", "episode_name", "episode_no", "season_no"]: episode[field] = match.group(field) # If the episode has no name it is given the same name as on imdb.com for consistency. if not episode["episode_name"]: episode["episode_name"] = "Episode #%s.%s" % (episode["season_no"], episode["episode_no"])
UPDATE websites SET laststatus = ?, lastcheck=current_timestamp WHERE id=?''', (newstatus, website.id)) conn.execute( ''' INSERT INTO checks (website_id,status,wait_ms) VALUES (?,?,?)''', (website.id, newstatus, wait_ms)) conn.commit() def check_website(conn, website): try: start = time.time() code = urllib.urlopen(website.url).getcode() end = time.time() wait_ms = 1000 * (end - start) if code == 200: update_website(conn, website, "OK", wait_ms) else: update_website(conn, website, "ERROR", wait_ms) except: update_website(conn, website, "ERROR", wait_ms) conn = sqlite3.connect('websites.db') database.init_db(conn) sites = get_websites(conn) for item in sites: check_website(conn, item) conn.close()
def init(): init_db()
try: from urllib.parse import urlparse, urljoin except ImportError: from urlparse import urlparse, urljoin from flask_login import LoginManager, login_user, logout_user, current_user, login_required from passlib.hash import pbkdf2_sha256 import database from werkzeug.utils import secure_filename from cassandra.cluster import Cluster import config import subprocess # initialize the app, thumbnail, db and s3 app = Flask(__name__) app.config.from_pyfile('config.cfg') database.init_db(app) db = database.db # set login manager parameters login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "login" login_manager.login_message = u"Please login to access this page." from model import Users from forms import RegistrationForm, LoginForm #set db parameters cluster = Cluster(config.cass_cluster_IP) session = cluster.connect('ecg')
#Loading environment variables from dotenv import load_dotenv load_dotenv() #Flask application creation from flask import Flask app = Flask(__name__) #Database connection from database import init_db db = init_db(app) #Setup Serialization & Deserialization from flask_marshmallow import Marshmallow ma = Marshmallow(app) #Controller Registration from controllers import registerable_controllers for controller in registerable_controllers: app.register_blueprint(controller)
elif request.method == 'DELETE': res, status = views.delete_author(author_id) return json(res, status=status) @app.route('/articles', methods=['POST', 'GET', 'DELETE']) async def articles_handler(request): if request.method == 'POST': res, status = views.add_articles(request.json) elif request.method == 'GET': res, status = views.get_articles() elif request.method == 'DELETE': res, status = views.delete_articles(request.json) return json(res, status=status) @app.route('/article/<article_id:int>', methods=['GET', 'PUT']) async def articles_id_handler(request, article_id): if request.method == 'GET': res, status = views.get_article(article_id) elif request.method == 'PUT': res, status = views.update_article(request.json, article_id) return json(res, status=status) if __name__ == "__main__": db.init_db() app.run(host=os.getenv('HOST'), port=os.getenv('PORT'), debug=True)
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) if test_config is None: app.config.from_pyfile("config.py") init_db(app) # ROUTES @app.route('/login', methods=['POST']) def login(): data = request.get_json() or {} if 'username' not in data or 'password' not in data: abort(422, 'username and password expected in request body') username = data['username'] password = data['password'] user = User.query.get(username) if not user: abort(422, 'username or password is not correct') if not user.checkpw(str(password)): abort(422, 'username or password is not correct') payload = {'sub': username, 'exp': datetime.now() + timedelta(days=30)} token = jwt.encode(payload, app.secret_key, 'HS256') return jsonify({'success': True, 'token': str(token, 'utf-8')}) @app.route("/private") @requires_auth def get_private(): return jsonify({ 'success': True, 'current_user': _request_ctx_stack.top.curr_user, 'content': '' }) @app.route('/public') def get_public(): return jsonify({'success': True, 'content': ''}) # ERROR HANDELERS @app.errorhandler(422) def un_processable(error): return jsonify({ 'success': False, 'message': error.description, 'code': 422 }), 422 @app.errorhandler(404) def not_found(error): return jsonify({ 'success': False, 'message': error.description, 'code': 404 }), 404 @app.errorhandler(405) def method_not_allowed(error): return jsonify({ 'success': False, 'message': error.description, 'code': 405 }), 405 @app.errorhandler(AuthError) def auth_error(error): return jsonify({ 'success': False, 'message': error.message, 'code': error.code }), error.code return app
def setUp(self): """Set up for the tests.""" self.db_fd, self.db_name = tempfile.mkstemp() database.set_engine('sqlite:///' + self.db_name) database.init_db() self.app = main.app.test_client()
# -*- coding: utf-8 -*- from datetime import timedelta from flask import Flask, url_for, redirect, session, flash import flask_login from werkzeug.wrappers import Response from database import init_db # from views.user import user_mod, set_hash # from models import User import views APP = Flask(__name__) APP.config.from_pyfile('musicresults.cfg') init_db(APP) # set_hash(APP.config.get('PWD_SALT')) APP.register_blueprint(views.band, url_prefix='/band') APP.register_blueprint(views.contest, url_prefix='/contest') APP.register_blueprint(views.contribute, url_prefix='/contribute') APP.register_blueprint(views.index) APP.register_blueprint(views.person, url_prefix='/person') APP.register_blueprint(views.testpiece, url_prefix='/test-piece') APP.register_blueprint(views.user, url_prefix='/user') APP.register_blueprint(views.venue, url_prefix='/venue') LOGIN_MANAGER = flask_login.LoginManager() LOGIN_MANAGER.init_app(APP) @APP.teardown_appcontext
def __init__(self): init_db()
def create_app(): """ Initializes the flask app object Returns: Flask: the initialized flask app """ app = Flask(__name__) app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 86400 # 1 day app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["SQLALCHEMY_ECHO"] = False app.config["SQLALCHEMY_RECORD_QUERIES"] = False app.config["model"] = model app.config[ "SECRET_KEY"] = "2jrlkfjoi1j3kljekdlasjdklasjdk139999d9d" # TODO: put this in config app.config["JWT_ACCESS_TOKEN_EXPIRES"] = datetime.timedelta(days=30) if app.config.get("SSL"): app.config.update(dict(PREFERRED_URL_SCHEME="https")) app.config["RUNMODE"] = "PRODUCTION" if os.getenv( CODE_COURT_PRODUCTION_ENV_VAR) else "DEVELOPMENT" # Add custom filters to Jinja2 # http://flask.pocoo.org/docs/0.12/templating/ app.jinja_env.filters["dt_to_str"] = util.dt_to_str app.jinja_env.filters["dt_to_date_str"] = util.dt_to_date_str app.jinja_env.filters["dt_to_time_str"] = util.dt_to_time_str setup_logging(app) app.logger.setLevel(logging.DEBUG) init_db() if not app.config["TESTING"]: setup_database(app) with app.app_context(): app.config["MAX_CONTENT_LENGTH"] = util.get_configuration( "max_output_length") * 1024 # kilobytes CORS(app, supports_credentials=True) JWTManager(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "auth.login_view" DebugToolbarExtension(app) app.logger.info("Setting up app") @login_manager.user_loader def load_user(username): return model.User.query.filter_by(username=username).scalar() app.register_blueprint(main, url_prefix="") app.register_blueprint(api, url_prefix="/api") app.register_blueprint(admin, url_prefix="/admin") app.register_blueprint(configurations, url_prefix="/admin/configurations") app.register_blueprint(clarifications, url_prefix="/admin/clarifications") app.register_blueprint(languages, url_prefix="/admin/languages") app.register_blueprint(problems, url_prefix="/admin/problems") app.register_blueprint(users, url_prefix="/admin/users") app.register_blueprint(runs, url_prefix="/admin/runs") app.register_blueprint(contests, url_prefix="/admin/contests") app.register_blueprint(defendant, url_prefix="/defendant") app.register_blueprint(auth, url_prefix="/admin") app.register_blueprint(utils, url_prefix="/admin/utils") @app.context_processor def inject_user(): return {} @app.route("/") def defendant_index(): return send_from_directory("static/defendant-frontend", "index.html") @app.route("/<path:path>") def all(path): try: return send_from_directory("static/defendant-frontend", path) except werkzeug.exceptions.NotFound as e: return send_from_directory("static/defendant-frontend", "index.html") @app.errorhandler(404) def page_not_found(e): return render_template("404.html"), 404 @app.errorhandler(401) @login_manager.unauthorized_handler def unauthorized(callback=None): if not current_user.is_authenticated: return render_template("auth/login.html"), 401 return render_template("401.html"), 401 @app.teardown_appcontext def teardown(exception=None): db_session.remove() @app.after_request def after_request(resp): if app.config.get("SQLALCHEMY_RECORD_QUERIES"): with open("/home/ben/sql", "a+") as f: f.write("=========\n{}:\n\n".format(request.url)) for q in get_debug_queries(): f.write("{}\n\n".format(q)) f.write("=========\n\n") return resp return app
def init_db(): database.init_db() return 'Init DB'
def initialize(): init_db() create_admin_account()
if user is None or user.role_id != 3: return _get_response("User not found", 404) positive = UserService.user_is_positive(db_session, user.id) if positive is None: return _get_response("Information not found", 404) else: return _get_response(positive.serialize(), 200, True) # --------- END API definition -------------------------- logging.basicConfig(level=logging.DEBUG) app = connexion.App(__name__) if "GOUOUTSAFE_TEST" in os.environ and os.environ["GOUOUTSAFE_TEST"] == "1": db_session = init_db("sqlite:///tests/user.db") else: db_session = init_db("sqlite:///user.db") app.add_api("swagger.yml") # set the WSGI application callable to allow using uWSGI: # uwsgi --http :8080 -w app application = app.app def _init_flask_app(flask_app, conf_type: str = "config.DebugConfiguration"): """ This method init the flask app :param flask_app: """ flask_app.config.from_object(conf_type)
def init(): """ Сервисный метод для инициализации базы данных """ init_db() return "Done"
def init(): init_db() #初始化db