def task_link(self, grab, task): for image in grab.doc.select('//img'): try: if (self.result_counter >= self.total): self.result_status = 'success' self.info = 'All images grabbed' self.request_item.status = self.result_status self.request_item.info = self.info db.session.commit() with app.app_context(): socketio.emit('finish', 'finish', namespace='/main') eventlet.sleep(0) self.stop() return src = image.attr('src') res = urllib.urlopen(src) http_message = res.info() if self.image_type != 'all' and self.image_type != http_message.type: continue hash = os.urandom(16).encode('hex') filename = hash + src.split('/')[-1] self.downloader.retrieve(src, 'app/static/images/' + filename) self.result_counter += 1 image_item = Image( self.request_item, src, filename) db.session.add(image_item) with app.app_context(): socketio.emit('grabed_count', self.result_counter, namespace='/main') eventlet.sleep(0) except Exception as e: continue
def task_initial(self, grab, task): self.request_item.title = grab.doc.select('//title').text() for elem in grab.xpath_list('//a[not(contains(@href, "http"))]'): if (self.result_counter >= self.total): self.result_status = 'success' self.info = 'All images grabbed' self.request_item.status = self.result_status self.request_item.info = self.info db.session.commit() with app.app_context(): socketio.emit('finish', 'finish', namespace='/main') eventlet.sleep(0) self.stop() return else: if elem.get('href') not in self.urls: self.urls.append(elem.get('href')) yield Task('link', url=elem.get('href')) if (self.result_counter != self.total): self.result_status = 'error' self.info = 'Not of all images grabbed' else: self.request_item.status = self.result_status self.request_item.info = self.info db.session.commit() with app.app_context(): socketio.emit('finish', 'finish', namespace='/main') eventlet.sleep(0) self.stop()
def levenshein_merger_groups(interactive=True, builder=None): if builder: matchlogger = builder else: matchlogger = MatchLogBuilder() query = delete(AlternateTranslatorNames).where(AlternateTranslatorNames.group == None) db.session.execute(query) if interactive: callback=askuser_callback else: callback=matchlogger.add_match_group print("fetching series") with app.app_context(): items = models.Translators.query.options( joinedload(Translators.alt_names) ).all() altn = [] for item in items: for name in item.alt_names: altn.append((name.id, name.name, name.cleanname)) print("Sorting names") altn.sort(key=lambda x: (x[1], x[0])) print("Searching for duplicates from %s names" % len(altn)) done = 0 for nid, name, cleanname in altn: with app.app_context(): matches = search_for_tlname(cleanname, nid, altn) if matches: try: namerow = models.AlternateTranslatorNames.query.filter(models.AlternateTranslatorNames.id==nid).one() match_to_group(namerow, matches, callback) except sqlalchemy.orm.exc.NoResultFound: print("Row merged already?") done += 1 if done % 10 == 0: print("Done %s items of %s" % (done, len(altn))) print(len(items)) print("wat?") if not interactive: matchlogger.save_log("./translatorname-matchset.json")
def load_user_ns(): from app import app, store # NOQA app.app_context().push() from app.models.user import User # NOQA from app.models.flower import Flower # NOQA from app.models.song import Song # NOQA from app.models.task import Task # NOQA from app.models.statistics import Statistics # NOQA from app.models.message import Message # NOQA from app.models.registration import Registration # NOQA return locals()
def levenshein_merger_series(interactive=True, builder=None): if builder: matchlogger = builder else: matchlogger = MatchLogBuilder() if interactive: callback=askuser_callback_series else: callback=matchlogger.add_match_series print("fetching series") with app.app_context(): items = models.Series.query.options( joinedload(Series.alternatenames) ).all() altn = [] for item in items: for name in item.alternatenames: altn.append((name.id, name.cleanname)) print("Sorting names") altn.sort(key=lambda x: (x[1], x[0])) print("Searching for duplicates from %s names" % len(altn)) done = 0 for nid, name in altn: if name == 'RoyalRoadL': continue with app.app_context(): matches = search_for_seriesname(name, nid) if matches: try: namerow = models.AlternateNames.query.filter(models.AlternateNames.id==nid).one() match_to_series(namerow, matches, callback) except sqlalchemy.orm.exc.NoResultFound: print("Row merged already?") done += 1 if done % 10 == 0: print("Done %s items of %s" % (done, len(altn))) print(len(items)) print("wat?") if not interactive: matchlogger.save_log("./seriesname-matchset.json")
def process_next_request(req): req.begin_processing() main.go(req.gtfs_url, req.agency_id, req.uuid) print 'Output files created!' req.finish_processing() with app.app_context(): send_file_ready_notification(req.email, req.gtfs_description, req.uuid)
def test_user_delete_imgur_child(self): """After using delete, does the child Imgur_User of a User get properly deleted from the site?""" with app.app_context(): with self.client: self.create_user() self.login_user() # link a imgur child model to test imgur_usr = Imgur_User(username="******", refresh_token="notactuallyatoken", user_id=current_user.id) db.session.add(imgur_usr) db.session.commit() # Make sure the imgur child exists imgur_usr = Imgur_User.query.first() self.assertFalse(imgur_usr is None) self.assertTrue(imgur_usr.user_id == current_user.id) # user delete response = self.client.post(url_for("account_delete"), data = {'password': "******"}) user = User.query.first() self.assertTrue(user is None) imgur_usr = Imgur_User.query.first() self.assertTrue(imgur_usr is None) return True
def send_test(): with app.app_context(): msg = Message("Hello", sender="*****@*****.**", recipients=["*****@*****.**",'*****@*****.**']) mail.send(msg)
def main(test=False): """Start tornado running hactar.""" conf = load(open('config.json', 'rb'))['production'] if test: config_app(app) else: secrets = load(open(conf['SECRETS'], 'rb')) conf['USERNAME'] = secrets['hactar']['username'] conf['PASSWORD'] = secrets['hactar']['password'] conf['SECRET_KEY'] = secrets['installed']['client_secret'] app.config.update(conf) setup('production') logpath = os.path.join(conf['LOG_DIR'], conf['LOG_MAIN']) handler = logging.handlers.RotatingFileHandler(logpath, maxBytes=100000, backupCount=4) fmtr = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') handler.setFormatter(fmtr) logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(handler) with app.app_context(): db.init_app(app) if not os.path.exists(conf['SQLALCHEMY_DATABASE_URI'].lstrip('sqlite:///')): with app.test_request_context(): db.create_all() app.celery_running = True app.logger.debug('starting app with config: %s' % app.config) http_server = HTTPServer(WSGIContainer(app)) http_server.listen(8080) IOLoop.instance().start()
def update_releases(forced=False): '''Uses the sources list in DB to search for contracts''' sources = db.session.query(Source).all() updated_sources = 0 for source in sources: print source.url if re.match("^http", source.url): #TODO: With the fixture we are not testing this part which is fairly sensitive r = requests.head(source.url) #If Last-Modified not avaiable, we always process now = datetime.now() source_update = now if 'Last-Modified' in r.headers: source_update = datetime(*eut.parsedate(r.headers['Last-Modified'])[:6]) if forced or source_update >= source.last_retrieve : load_source(source) updated_sources += 1 else: load_source(source) updated_sources += 1 if updated_sources > 0: compute_supplier_size() #Let's flush the cache cache.init_app(app, config={'CACHE_TYPE': 'simple'}) with app.app_context(): cache.clear()
def create_user(self, username="******", email="*****@*****.**", pwd="password"): """Helper function to create a User entry in database through SQLAlchemy""" with app.app_context(): user = User(username=username, email=email, pwd=bcrypt.generate_password_hash(pwd)) db.session.add(user) db.session.commit()
def init_db(): """Creates the database tables.""" with app.app_context(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
def execute_script(file_name): with app.app_context(): db = connect_db() with open(file_name, mode='r') as f: db.cursor().executescript(f.read()) db.commit() db.close()
def setUp(self): self.app = app.test_client() self.app_context = app.app_context() self.app_context.push() db.drop_all() db.create_all() self.admin_role = self._create_admin_role()
def createWebpageGroup(form): """ Create webpageGroup Creates a webpageGroup for the current manager if it doesn't already exist (there can't be two webpageGroups with the same name and manager). Args: form: The form containing information about the webpageGroup that has to be created. """ if form.validate_on_submit(): # Check that the webpageGroup doesn't already exist. webpageGroup = db.session.query(WebpageGroup). \ filter(WebpageGroup.name == form.name.data, \ WebpageGroup.managerId == session['id']).first() if webpageGroup is None: flash("The webpage group was created", 'message') with app.app_context(): wpg = WebpageGroup(name = form.name.data, \ email = form.email.data, \ address = form.address.data, \ telephone = form.telephone.data, \ url = form.url.data, \ managerId = session['id']) db.session.add(wpg) db.session.commit() else: flash ("That webpage group already exists", 'error') else: flash_errors(form)
def send_async_email(app, msg): '''Because it is a separate thread, the application context required by Flask-Mail will not be automatically set for us, so the app instance is passed to the thread, and the application context is set up manually, like we did above when we sent an email from the Python console.''' with app.app_context(): mail.send(msg)
def main(): """Main entry point for script.""" with app.app_context(): #db.metadata.create_all(db.engine) if User.query.all(): print 'A user already exists! Create another? (y/n):', create = raw_input() if create == 'n': return users = [u.username for u in User.query.all()] print 'Enter username: '******'User already exists. Enter new username: '******'Enter password: '******'User added.' users = User.query.all() print(users)
def __call__(self, *args, **kwargs): with app.app_context(): # Application context for databases g.mongo = app_mongo g.redis = app_redis return task_base.__call__(self, *args, **kwargs)
def publish(uuid, **kw): from app import app with app.app_context(): params = {'uuid': uuid, 'extra': kw.pop('extra', None), 'type': kw.pop('type', None)} params.update(kw) sse.publish(params, type='login')
def start(): global threads, exitFlag time.sleep(2) exitFlag = 0 with app.app_context(): for thread in threads: thread.start()
def setUp(self): app.testing = True app.port = 8943 with app.app_context(): self.app = app.test_client() self.db = TESTDB_SQLALCHEMY_DATABASE_URI
def setUpClass(cls): # Make sure database exists app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' app.config['DEBUG'] = False app.config['PROPAGATE_EXCEPTIONS'] = True with app.app_context(): db.init_app(app)
def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = BaseTest.SQLALCHEMY_DATABASE_URI with app.app_context(): db.init_app(app) db.create_all() self.app = app.test_client() self.app_context = app.app_context
def editManager(form): """ Edit manager info Edit the information for the currently logged-in manager (from form) Args: form: The form contains information about the manager that has to be edited """ if form.validate_on_submit(): manager = db.session.query(Manager). \ filter(Manager.id == session['id']).first() if manager is not None: with app.app_context(): manager.name = form.name.data manager.email = form.email.data manager.address = form.address.data manager.telephone = form.telephone.data manager.username = form.username.data db.session.commit() flash("Your information was edited", 'message') else: flash("Something went wrong", 'error') else: flash_errors(form)
def init(): """ Fixture for test initialisation """ # App configuration overide app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.config['SERVER_NAME'] = 'localhost' # DB creation db.create_all() user = User(nickname='utest', email='*****@*****.**', password='******', active=True, confirmed_at=datetime.utcnow(), auth_token='ddg56@dgfdG°dkjvk,') db.session.add(user) db.session.commit() # Context setup context = app.app_context() context.push() yield db.session.remove() db.drop_all() context.pop()
def on_message(self, headers, message): """ Handler on message """ LOGGER.info("=" * 72) LOGGER.info('Message headers:\n%s', headers) LOGGER.info('Message body:\n%s', message) libvirt_dashboard_build = headers.get('libvirt_dashboard_build') libvirt_dashboard_id = headers.get('libvirt_dashboard_id') polarion_testrun = headers.get('polarion_testrun') message = json.loads(message) status = message.get('status') log_url = message.get('log-url') with app.app_context(): if status == "passed": count = Run.query.filter(Run.id == libvirt_dashboard_id).update({ "submit_status": status, "submit_log": log_url, "submit_date": datetime.datetime.now() }) else: count = Run.query.filter(Run.id == libvirt_dashboard_id).update({ "submit_status": status, "submit_log": log_url, }) Run.query.session.commit() if not count: LOGGER.error("No matching test run for ID: {}".format(libvirt_dashboard_id)) else: LOGGER.info("Updated Test run ID: {}".format(libvirt_dashboard_id))
def editPass(form): """ Edit manager info Change the password for the currently logged-in manager (from form) Args: form: The form contains the old password and the new password. """ if form.validate_on_submit(): manager = db.session.query(Manager). \ filter(Manager.id == session['id']).first() if manager is not None: if form.newPass1.data == form.newPass2.data: if manager.checkPassword(form.oldPass.data): with app.app_context(): manager.password = form.newPass1.data db.session.commit() flash("Your information was editied", 'message') else: flash("The password is not correct", 'error') else: flash("The passwords are not equal", 'error') else: flash("Something went wrong", 'error') else: flash_errors(form)
def cycle_switches(self): self.log.info("Emitting message: %s, %s", self.rollup_time, time.time()) with app.app_context(): exp = config.CYCLE_EXPERIMENTS[self.experiment_idx] self.experiment_idx = (self.experiment_idx + 1) % len(config.CYCLE_EXPERIMENTS) npts = EXPERIMENT_CONFIGS[exp]['npts'] startf, stopf = EXPERIMENT_CONFIGS[exp]['start'], EXPERIMENT_CONFIGS[exp]['stop'] msg = { "src-guid" : "nooooooope", "switch-matrix" : { "experiment-1" : exp == 1, "experiment-2" : exp == 2, "experiment-3" : exp == 3, "experiment-4" : exp == 4, }, 'start-stop' : [startf, stopf], 'no-points' : npts, } app.config['ARBITER'].set_experiment(msg["switch-matrix"]) app.config['ARBITER'].set_num_points(npts) app.config['ARBITER'].set_start_stop_freq(startf, stopf) socketio.emit('config', msg, broadcast=True, namespace='/vna_interface')
def test_retrieveRecipe(self): with app.app_context(): request = self.client.get('/api/v1/recipes/1', data=dict( key=app.config.API_KEY)) print(request.data) assert(False) assert(json.loads(str(request.data)) == data[0])
def main(): """Main entry point for script.""" with app.app_context(): db.metadata.create_all(db.engine) if User.query.all(): print 'A user already exists! Create another? (y/n):', create = raw_input() if create == 'n': return print 'Enter email address: ', email = raw_input() password = getpass() assert password == getpass('Password (again):') print password m = md5.new() m.update(password) print 'Enter nickname: ' nickname = raw_input() print 'Is admin y/n? ' answer = raw_input() if answer == 'y': user = User(nickname=nickname, email=email, password=m.hexdigest(), is_admin=True) else: user = User(nickname=nickname, email=email, password=m.hexdigest()) print m.hexdigest() db.session.add(user) db.session.commit() print 'User added.'
def send_async_email(app, msg): with app.app_context(): try: mail.send(msg) except ConnectionRefusedError: raise InternalServerError("[MAIL SERVER] not working")
def delete_duplicate_releases(): with app.app_context(): api_handlers_admin.delete_duplicate_releases(None, admin_override=True)
def test_get_db(self): with app.app_context(): db = db_functions.get_db() assert (db != None)
from dotenv import load_dotenv load_dotenv() from flask import jsonify from app import app, db from app.models import User, Note, Notebook, Tag with app.app_context(): db.drop_all() db.create_all()
def tearDown(self): # Database is blank with app.app_context(): db.session.remove() db.drop_all()
def setUpClass(cls): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' app.config['DEBUG'] = False app.config['PROPAGATE_EXCEPTIONS'] = True with app.app_context(): db.init_app(app)
def clean_tags(): with app.app_context(): api_handlers_admin.clean_tags(None, admin_override=True)
def fix_escaped_quotes(): with app.app_context(): api_handlers_admin.fix_escaped_quotes(None, admin_override=True)
def tearDown(self): with app.app_context(): db.session.remove() db.drop_all()
def client_with_db(): db, app.config['DATABASE'] = tempfile.mkstemp( ) # Tworzona jest baza danych w folderze tymczasowym o losowej nazwie with app.app_context(): init_db() return app.test_client()
def monitor(id, type): with app.app_context(): status = '成功执行但未监测到变化' global_content = None try: if type == 'html': task = Task.query.filter_by(id=id).first() url = task.url selector_type = task.selector_type selector = task.selector is_chrome = task.is_chrome regular_expression = task.regular_expression mail = task.mail wechat = task.wechat name = task.name rule = task.rule headers = task.headers last = Content.query.filter_by(task_id=id, task_type=type).first() if not last: last = Content(id) last_content = last.content content = get_content(url, is_chrome, selector_type, selector, regular_expression, headers) global_content = content status_code = is_changed(rule, content, last_content) logger.info( 'rule: {}, content: {}, last_content: {}, status_code: {}'. format(rule, content, last_content, status_code)) if status_code == 1: status = '监测到变化,但未命中规则,最新值为{}'.format(content) last.content = content db.session.add(last) db.session.commit() elif status_code == 2: status = '监测到变化,且命中规则,最新值为{}'.format(content) msg = wraper_msg(content, url) send_message(msg, name, mail, wechat) last.content = content db.session.add(last) db.session.commit() elif status_code == 3: status = '监测到变化,最新值为{}'.format(content) msg = wraper_msg(content, url) send_message(msg, name, mail, wechat) last.content = content db.session.add(last) db.session.commit() elif type == 'rss': rss_task = RSSTask.query.filter_by(id=id).first() url = rss_task.url name = rss_task.name mail = rss_task.mail wechat = rss_task.wechat last = Content.query.filter_by(task_id=id, task_type=type).first() if not last: last = Content(id, 'rss') last_guid = last.content item = get_rss_content(url) if item['guid'] != last_guid: global_content = content content = wraper_rss_msg(item) send_message(content, name, mail, wechat) last.content = item['guid'] db.session.add(last) db.session.commit() status = '监测到变化,最新值:' + item['title'] except FunctionTimedOut: logger.error(traceback.format_exc()) status = '解析RSS超时' except Exception as e: logger.error(traceback.format_exc()) status = repr(e) if '其中一种' in status: last.content = global_content db.session.add(last) db.session.commit() task_status = TaskStatus.query.filter_by(task_id=id, task_type=type).first() task_status.last_run = datetime.now() task_status.last_status = status db.session.add(task_status) db.session.commit()
def flatten_series_by_url(): with app.app_context(): api_handlers_admin.flatten_series_by_url(None, admin_override=True)
def test_db_entries(self): with app.app_context(): keys = db_functions.get_keys()
def test_service_success_case(self): with app.test_client() as client: with app.app_context(): # if this fails it raises an error and if it succeeds we get a dictionary back response = weather_service.get_weather_by_city_name("Vancouver") self.assertIsInstance(response, dict)
def run_shell(): app.app_context().push() # nie kasuje db db.create_all()
def setUpClass(cls): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' app.config['DEBUG'] = False with app.app_context(): db.init_app(app)
def setUpClass(cls): # This is an analogue of 'Before All' in Jasmine app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' with app.app_context(): db.init_app(app)
def send_async(app, message): ''' Send the mail asynchronously. ''' with app.app_context(): mail.send(message)
def setUp(self): app.config['TESTING'] = True self.app = app.app_context().push() self.client = app.test_client() self.db = db self.db.recreate()
import app.core.dao as dao import pymysql from app.utils.misc import convert_string_to_datetime from app.utils.Error import CustomError import app.core.services as service import json from datetime import datetime, timedelta import re import argparse from app import app ctx = app.app_context() ctx.push() def lesson_week_list(lesson_week): lesson_weeks = list() lesson_week_blocks = lesson_week.replace(' ', '').split(',') for lesson_week_block in lesson_week_blocks: if lesson_week_block == '': continue weeks = lesson_week_block.replace(' ', '').split('-') if len(weeks) == 2: week_begin = int(weeks[0]) week_end = int(weeks[1]) [ lesson_weeks.append(str(week)) for week in range(week_begin, week_end + 1) ] else: lesson_weeks.append(weeks[0])
def setUp(self): self.app = app.test_client() with app.app_context(): self.songs = mongo.db.songs self.song_id = None
def send_async_email(app, msg): """异步电子邮件""" with app.app_context(): mail.send(msg)
def sendMail(content): with app.app_context(): msg = Message(content, recipients=['*****@*****.**'], body=content) mail.send(msg)
def client(app_config): with app.app_context(): yield app.test_client()
from flask import Flask from models import db, Feira import csv from app import app app.debug = True app.app_context().push() with app.app_context(): db.create_all() # Opening the csv file git comm with open('data/DEINFO_AB_FEIRASLIVRES_2014.csv') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') # Skipping the headers csv_reader.__next__() # Reading the table, line by line and adding to transaction for row in csv_reader: feira = Feira() feira.id = row[0] feira.long = row[1] feira.lat = row[2] feira.setcens = row[3] feira.areap = row[4] feira.coddist = row[5] feira.distrito = row[6] feira.codsubpref = row[7] feira.subprefe = row[8]
def tearDown(self): # make sure database is blunk with app.app_context(): db.session.remove() db.drop_all()
def send_async_email(app, msg): with app.app_context(): mail.send(msg)
def init_db(): with app.app_context(): db = get_db() with app.open_resource(os.path.join(app.root_path, 'data', 'database', 'initialization.sql'), mode='r') as f: db.cursor().executescript(f.read()) db.execute( 'insert into balance_sheet (cash, accounts_receivable, inventory, land_and_buildings, equipment,\ furniture_and_fixtures, accounts_payable, notes_payable, accruals, mortgage)\ values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ["200000", "0", "12360", "0", "0", "0", "0", "0", "0", "0"]) db.execute( 'insert into income_statement (sales, cost_of_goods, payroll, payroll_withholding, bills,\ annual_expenses, other_income) values (?, ?, ?, ?, ?, ?, ?)', ["1000000", "228000", "0", "0", "0", "0", "0"]) db.execute( 'insert into inventory_sell (can_be_built_units, complete_units, total_value)\ values (?, ?, ?)', ["0", "4000", "10000"]) db.execute( "insert into employees (last_name, first_name, address_line_1, address_line_2, city_name, state_name, zip_code,\ social_security_number, number_of_withholdings, salary) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [ "Smith", "John", "111 Front Street", "Apartment 111", "Champaign", "Illinois", "61820", "123-45-6789", "0", "12500" ]) db.execute( "insert into customers (company_name, last_name, first_name, address_line_1, address_line_2,\ city_name, state_name, zip_code, price) values (?, ?, ?, ?, ?, ?, ?, ?, ?)", ["Amazon", "", "", "", "", "", "", "", "2.5"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Wheels", "0.01", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Wheels", "0.01", "10000", "100"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Windshield Glass", "0.05", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Windshield Glass", "0.05", "10000", "500"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Interior", "0.05", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Interior", "0.05", "1000", "50"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Tank", "0.10", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Tank", "0.10", "10000", "100"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Axles", "0.01", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Axles", "0.01", "10000", "100"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Cab", "0.10", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Cab", "0.10", "10000", "1000"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Body", "0.10", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Body", "0.10", "100", "10"]) db.execute( "insert into vendors (company_name, part, price_per_unit, address_line_1, address_line_2,\ city_name, state_name, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?)", ["", "Box", "0.05", "", "", "", "", ""]) db.execute( "insert into inventory_buy (part, price_per_unit, quantity, total_value) values (?, ?, ?, ?)", ["Box", "0.05", "10000", "500"]) db.commit() print('Initialization of database is completed.')
from app import app, db, redis from rq import get_current_job from app.models import Task, Download, User from app.routes import get_response, get_content_list, reg_biquge, get_content_text import os from config import Config from hashlib import md5 from datetime import datetime app.app_context().push() def _set_task_progress(progress): job = get_current_job() if job: job.meta['progress'] = progress job.save_meta() task = Task.query.get(job.get_id()) # task.user.add_notification('task_progress', {'task_id': job.get_id(), 'progress': progress}) if progress >= 100: task.complete = True db.session.commit() def download(user_id, source_id, book_id): try: d = Download.query.filter_by(book_id=book_id, source_id=source_id).first() # 这里必须使用id查询user而不能直接使用current_user u = User.query.get(user_id)
def setUp(self): app.config['TESTING'] = True app.app_context() app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test1.db' self.app = app.test_client() db.create_all()