Пример #1
0
def send_email(msg, retries):
    mime = MIMEMultipart(msg["subtype"])
    mime['Subject'] = msg["title"]
    mime['From'] = formataddr(msg["sender"])
    mime['To'] = ", ".join(msg["recipients"])

    # Attatch html
    msgHtml = MIMEText(msg["html"], 'html')
    mime.attach(msgHtml)

    # Attach images
    with app.open_resource("static/sg-logo.png") as fp:
        sg_logo = MIMEImage(fp.read())
        sg_logo.add_header('Content-ID', '<sg-logo>')
        mime.attach(sg_logo)
        fp.close()

    with app.open_resource("static/paw.png") as fp:
        sg_paw = MIMEImage(fp.read())
        sg_paw.add_header('Content-ID', '<sg-paw>')
        mime.attach(sg_paw)
        fp.close()

    try:
        server = smtplib.SMTP(config.MAIL_SERVER, config.MAIL_PORT)
        server.starttls()
        server.login(config.MAIL_USERNAME, config.MAIL_PASSWORD)
        server.sendmail(msg["sender"][1], msg["recipients"], mime.as_string())

    except Exception as e:
        if retries != 0: raise

    server.quit()
def app():
    app = get_test_app()

    with app.app_context():

        server_config = ConfigManager.get_instance().get_server_config()
        application_root = ConfigManager.get_instance().get_application_root()

        app.register_blueprint(incidence_controller,
                               url_prefix=application_root)
        app.register_blueprint(municipality_controller,
                               url_prefix=application_root)
        app.register_blueprint(swaggerui_controller,
                               url_prefix=application_root)

        app.config['DEVELOPMENT'] = server_config["development"]

        with app.open_resource(
                "tests/api_blackbox/testdata/dump_municipalities.sql"
        ) as f_municipalities:
            with app.open_resource(
                    "tests/api_blackbox/testdata/dump_incidences.sql"
            ) as f_incidences:
                engine = db.get_engine()

                with engine.connect() as con:

                    create_incidence = '''
                    CREATE TABLE incidence (
                        "incidencesId" integer NOT NULL,
                        "bfsNr" integer NOT NULL,
                        date date NOT NULL,
                        incidence double precision NOT NULL,
                        cases integer NOT NULL,
                        cases_cumsum_14d integer NOT NULL
                    );
                    '''

                    create_municipality = '''
                    CREATE TABLE municipality (
                        "bfsNr" integer NOT NULL,
                        name character varying(256) NOT NULL,
                        canton character varying(2) NOT NULL,
                        area double precision NOT NULL,
                        population integer NOT NULL,
                        region character varying(256) NOT NULL
                    );
                    '''

                    con.execute(create_municipality)
                    con.execute(create_incidence)

                    query_municipalities = text(
                        f_municipalities.read().decode("utf8"))
                    con.execute(query_municipalities)
                    query_incidences = text(f_incidences.read().decode("utf8"))
                    con.execute(query_incidences)

        yield app
Пример #3
0
def runit():
    with app.open_resource(
            'static/descriptionText/HomeResearchDescription.txt') as f:
        homecontent = f.read().decode('utf-8')
    with app.open_resource('static/descriptionText/ResearchAbout.txt') as f:
        researchcontent = f.read().decode('utf-8')
    return render_template('home.html',
                           homedescription=homecontent,
                           researchdescription=researchcontent)
Пример #4
0
def create_message(subject,
                   user=defaultUser,
                   filename="FILENAME",
                   result="RESULT",
                   modelType="MODEL TYPE"):

    msg = Message('Alert C19 web App',
                  sender='*****@*****.**',
                  recipients=['*****@*****.**'])

    if subject == 'inscription':
        msg.body = "Un nouvel utilisateur s'est inscrit.\nNom :" + \
            user['nom'] + "\nPrénom :" + \
            user['prenom'] + "\nMail :" + user['mail']
        print('Mail create')
        return msg
    elif subject == 'prediction':
        msg.body = "L'utilisateur " + user['nom'] + " " + user['prenom'] + " a soumis le fichier " + \
            filename + ".\nRésultat : " + result + ".\nModel utilisé :" + modelType + "."
        with app.open_resource("uploads/" + filename) as fp:
            msg.attach("uploads/" + filename,
                       magic.from_file('uploads/' + filename, mime=True),
                       fp.read())
        print('Mail create')
        return msg
    elif subject == 'rapport':
        pass
    else:
        print('Error invalid parameter in mail.py')
Пример #5
0
def create_db():
    '''Функція для створення таблиць БД'''
    db = view.connect_db()
    with app.open_resource('sq_db.sql', mode='r') as f:
        db.cursor().executescript(f.read())
    db.commit()
    db.close()
Пример #6
0
def init_db():
    # Delete the database file
    try:
        os.remove(app.config['DATABASE'])
    except OSError:
        pass

    try:
        os.remove(app.config['DATABASE'])
    except OSError:
        pass

    try:
        dir_name = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
        files = os.listdir(dir_name)

        for item in files:
            if any(item.lower().endswith(ext)
                   for ext in app.config['IMAGE_EXTENSIONS']):
                os.remove(os.path.join(dir_name, item))
    except OSError:
        pass

    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Пример #7
0
def send_email(path_to_file, recipient):
    app.logger.info("Preparing email...")

    # prepare email attachment
    # NOTE: when using the app context you automatically go into the app
    # folder and thus you need to remove the first part of the path
    with app.open_resource(str(Path(*path_to_file.parts[1:]))) as file:
        attachment = Attachment(
            filename=path_to_file.name,
            data=file.read(),
            content_type="application/vnd.ms-excel",
        )

    # send email
    app.logger.info("Start sending email")

    with app.app_context():
        mail.send_message(
            subject="Wordified file",
            sender=app.config["ADMINS"][0],
            recipients=[recipient],
            body=
            ("Dear user,\r\n\nPlease find attached your Wordified file. "
             "It contains two sheets: one with the positive indicators for "
             "each label and one with the negative indicators (note that if "
             "you have only two labels, the positive indicators of one label "
             "are the negative ones of the other, and vice versa).\r\nIf you "
             "do not see any indicators, you might have provided too few texts "
             "per label.\r\n\nYour Wordify Team"),
            attachments=[attachment],
        )
    app.logger.info("Email sent")

    # delete file from memory
    path_to_file.unlink()
Пример #8
0
def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
    print("database initialized")
Пример #9
0
def index():
    with app.open_resource('Dublin.json', 'r') as f:
        mydata = json.load(f)
        location = []
        name = []
        number = []
        address = []
        lat = []
        long = []
        j = 0
        for i in mydata:
            number.append(mydata[j]['number'])
            name.append(mydata[j]['name'])
            address.append(mydata[j]['address'])
            lat.append(mydata[j]['latitude'])
            long.append(mydata[j]['longitude'])

            j += 1
        address = json.dumps(address).replace("\'", "\\'")
        name = json.dumps(name).replace("\'", "\\'")
        number = json.dumps(number)
        lat = json.dumps(lat)
        long = json.dumps(long)
    returnDict = {}
    returnDict['user'] = '******'
    returnDict['title'] = 'Dublin Bikes'
    return render_template("index.html",
                           **returnDict,
                           number=number,
                           address=address,
                           lat=lat,
                           long=long)
Пример #10
0
def sendmail(mail_id):
   msg = Message("Your Attendance QR-Code.",
            recipients=[mail_id],
            sender='*****@*****.**')
   with app.open_resource("../qr.png") as fp:
      msg.attach("qr.png", "image/png", fp.read())
   mail.send(msg)
Пример #11
0
def init_db():
    db = get_db()

    with app.open_resource('schema.sql',mode = 'r') as f:
        db.cursor().executescript(f.read())

    db.commit()
Пример #12
0
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()
Пример #13
0
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()
Пример #14
0
def contact():
    form = SubscriberForm()
    if request.method == "POST":
        subscriber_name = request.form["subscriber_name"]
        email = request.form["email"]

        subscriber = Subscriber(subscriber_name=subscriber_name, email=email)
        db.session.add(subscriber)
        db.session.commit()

        message_subject = "10 Color Theory Basics Everyone Should Know"
        message_body = "Thank you for choosing Inspire Blog! Enjoy new ideas every day :) \n" \
                       "To start with - please follow our guide on Color Theory Basics."

        msg = Message(subject=message_subject,
                      body=message_body,
                      sender="*****@*****.**",
                      recipients=[email])

        filename = "10 Color Theory Basics Everyone Should Know.pdf"

        with app.open_resource("static/images/messages/" + filename) as fp:
            msg.attach(filename,
                       "10 Color Theory Basics Everyone Should Know/pdf",
                       fp.read())

        mail.send(msg)
        flash("Message sent")
        return redirect(url_for("index"))

    return render_template("index.html")
Пример #15
0
def email_log(message):
    msg = Message("%s Notice Fitboard" % (message), recipients=["*****@*****.**"])
    msg.body = "NOTICE %s \n Logile Attached \n" % (message)
    with app.open_resource("fitboard.log") as fp:
        msg.attach("fitboard.log", "text/plain", fp.read())
    mail.send(msg)
    return
Пример #16
0
def upload_cards(album):
    images = client.get_album_images(album)
    with app.open_resource('static/data/cards.json') as f:
        data = sorted(json.load(f))
    for card, image in zip(data, images):
        db.session.add(models.Card(value=card, image=image.link))
    db.session.commit()
Пример #17
0
def init_db():
    print 'sync db...'
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read())
        db.commit()
    print 'done !'
Пример #18
0
def send_email():
    @threaded
    def send_async_email(msg):
        with app.app_context():
            mail.send(msg)

    email_form = EmailForm()
    if email_form.validate_on_submit():
        _id = hashids.encode(current_user.id)
        data = f"{_id}:{request.args.get('data')}"
        qr_file = get_qr_file(encode_data(data), 'JPEG')
        target_email = email_form.email.data
        message = Message('Электронный пропуск',
                          sender=Config.MAIL_ADMIN,
                          recipients=[target_email])
        message.body = 'Ваш электронный пропуск во вложении'
        with app.open_resource(qr_file.name) as fp:
            message.attach(qr_file.name, "image/jpeg", fp.read())
            with app.app_context():
                send_async_email(message)

        return flask.redirect(url_for('get_qr_code'))

    return flask.render_template('email_send.html',
                                 email_form=email_form,
                                 id=id)
Пример #19
0
def sendmail(mail_id):
    msg = Message("Your Attendance QR-Code.",
                  recipients=[mail_id],
                  sender='*****@*****.**')
    with app.open_resource("../qr.png") as fp:
        msg.attach("qr.png", "image/png", fp.read())
    mail.send(msg)
Пример #20
0
def init_db():
    """
    initialize a database
    created a database schema according to schema.sql
    """
    with app.app_context():
        print('\n\n> Checking if the geopy module is working, entered (lat, long) as (10, 10)')
        print(latlong_to_address(10, 10))
        db = get_db()
        print('\n\n> Started with the creating the database')
        with app.open_resource('schema.sql', mode='r') as f:
            store= f.read()
            db.cursor().executescript(store)
        db.commit()
        print('\n\n> Created the database')
        print(query_db("SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';"), '\n')
        create_the_databse();
        check_farmer()
        check_banks()
        check_transporter()
        check_authorities()
        check_shopvendor()
        bank_rtf = []
        crop_price1 = []
        for i in range(3):
            bank_rtf.append(bank_rateofff(i))
            crop_price1.append(crop_price(i))
        crop_sum1 = crop_sum()
        shopvendor_auth1 = shopvendor_auth()
        storage_auth1 = storage_provider_auth()
        #SVID nikalde form se yaha
        SVID = "SV_191"
        shop_inv1 = shop_inv(SVID)
Пример #21
0
def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('alpinklubben.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
        print("created database")
Пример #22
0
def email_log(message):
    msg = Message("%s Notice Fitboard" % (message),
                  recipients=["*****@*****.**"])
    msg.body = "NOTICE %s \n Logile Attached \n" % (message)
    with app.open_resource("fitboard.log") as fp:
        msg.attach("fitboard.log", "text/plain", fp.read())
    mail.send(msg)
    return
Пример #23
0
def podcasts():
    with app.open_resource('podcast_genres.json') as f:
        genres = json.load(f)
    form = PodcastSearchForm()
    return render_template('podcasts.html',
                           title='Podcasts',
                           form=form,
                           genres=genres['genres'])
Пример #24
0
 def read_txt():
     with app.open_resource('static/usa.txt') as dictionary:
         dictionary_words = dictionary.read().splitlines()
         events = len(dictionary_words)
         dictionary_dict = {}
     for x in range(events):
         dictionary_dict[x] = dictionary_words[x].decode()
     return dictionary_dict
Пример #25
0
def send_email():
    for addr in get_mails():
        msg = Message("XML", sender="*****@*****.**", recipients=[addr])
        msg.body = "XML data"
        for xml in glob.glob(APP_STATIC+"/*.xml"):
            with app.open_resource(xml) as fp:
                msg.attach(basename(xml), "application/xml", fp.read())
        mail.send(msg)
    return redirect('/nodes')
Пример #26
0
def api(urn):
    with app.open_resource("static/canonical-greekLit.tracking.json", "r") as f:
          TrackingData = json.loads(f.read())
    tracking_data = TrackingData[urn]
    if tracking_data == None:
        flash('Tracking data for %s not found.' % urn)
        return redirect(url_for('search'))
    return render_template('api.html', 
       json =  "{'"+ urn + "':" + json.dumps(TrackingData[urn], sort_keys=True, indent=4) + "}")
def init_db_if_needed():
    db = get_db()
    res = db.execute('SELECT count(*) FROM sqlite_master WHERE type=\'table\' AND name=\'change_table\'').fetchone()

    if res[0] == 0:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.execute('CREATE TABLE \'change_table\' (cht_id INTEGER PRIMARY KEY DESC)')
        db.commit()
Пример #28
0
def sendmail(mail_id):
   msg = Message("Your Attendance QR-Code.",
            recipients=[mail_id],
            sender='*****@*****.**',#app.config['DEFAULT_SENDER'],#'*****@*****.**',
            html="<p>&nbsp;&nbsp;&nbsp;QR code has been generated please display it near the system while coming. This QR-Code is secret any violation will subject invalidation.</p>"
            )
   with app.open_resource("../qr.png") as fp:
      msg.attach("qr.png", "image/png", fp.read())
   mail.send(msg)
Пример #29
0
def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('../schema.sql', 'r') as f:
            db.cursor().executescript(f.read())
        for key in path.keys():
            db.execute(
                'insert into entries (full, alias, password) values (?, ?, ?)',
                ('', path[key], ''))
        db.commit()
Пример #30
0
def init_db():

    # Setup DB location
    app.config['DATABASE'] = DATABASE

    db = get_db()

    # Use the schema
    with app.open_resource('schema.sql') as f:
        db.executescript(f.read().decode('utf8'))
Пример #31
0
def init_db():
    """
    initialize a database
    created a database schema according to schema.sql
    """
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Пример #32
0
def sendmail(mail_id):
    msg = Message(
        "Your Attendance QR-Code.",
        recipients=[mail_id],
        sender='*****@*****.**',  #app.config['DEFAULT_SENDER'],#'*****@*****.**',
        html=
        "<p>&nbsp;&nbsp;&nbsp;QR code has been generated please display it near the system while coming. This QR-Code is secret any violation will subject invalidation.</p>"
    )
    with app.open_resource("../qr.png") as fp:
        msg.attach("qr.png", "image/png", fp.read())
    mail.send(msg)
Пример #33
0
def send_techcard(to, subject, filename, **kwargs):
    msg = Message(subject, recipients=[to])
    with app.open_resource(filename) as file:
        filename = filename.replace('static/', '')
        msg.attach(
            filename,
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            file.read())
    async_mail = Thread(target=send_async_email, args=[app, msg])
    async_mail.start()
    return async_mail
Пример #34
0
def init_db():
    db = connect_db()

    with app.open_resource(SCHEMA_SQL, mode="r") as rf:
        db.cursor().executescript(rf.read())
    db.commit()

    if not query_db(
            db, 'SELECT * FROM "users" WHERE "username" = "demo"', one=True):
        sql = 'INSERT INTO "users" ("username", "pw_hash", "pms") VALUES ("demo", "pbkdf2:sha1:1000$JRgRzRjc$6f868a04660633294eea9cf737a032a1e7eecb7d", "admin");'
        write_db(db, sql)
Пример #35
0
def init_db():
    """Initializes the database."""
    db = get_db()
    with app.open_resource('schema.sql', mode='r') as f:
        linha = f.read()
        try:
            db.cursor().executescript(linha)
        except:
            print "Unexpected error:", sys.exc_info()[0]
            print ('Erro:', linha) 
    db.commit()
Пример #36
0
def display(urn):
    with app.open_resource("static/canonical-greekLit.tracking.json","r") as f:
          TrackingData = json.loads(f.read())
    tracking_data = TrackingData[urn]
    if tracking_data == None:
        flash('Tracking data for %s not found.' % urn)
        return redirect(url_for('search'))
    return render_template('display.html', 
        title = "Tracking information for " + urn,
        urn = urn, 
        f = tracking_data)
Пример #37
0
def send():
    res = start()
    cv2.imwrite('app//app//predict.jpg', crop_img)
    msg = Message("Оповещение",
                  sender="*****@*****.**",
                  recipients=[mn.adress])
    msg.body = "г.Подольск (улица Ленинцев) " + res.json.get('result')
    with app.open_resource("predict.jpg") as fp:
        msg.attach('predict.jpg', "image/jpg", fp.read())
    mn.mail.send(msg)
    return jsonify(result="Письмо отправлено")
Пример #38
0
def display(urn):
    with app.open_resource("static/canonical-greekLit.tracking.json",
                           "r") as f:
        TrackingData = json.loads(f.read())
    tracking_data = TrackingData[urn]
    if tracking_data == None:
        flash('Tracking data for %s not found.' % urn)
        return redirect(url_for('search'))
    return render_template('display.html',
                           title="Tracking information for " + urn,
                           urn=urn,
                           f=tracking_data)
Пример #39
0
def api(urn):
    with app.open_resource("static/canonical-greekLit.tracking.json",
                           "r") as f:
        TrackingData = json.loads(f.read())
    tracking_data = TrackingData[urn]
    if tracking_data == None:
        flash('Tracking data for %s not found.' % urn)
        return redirect(url_for('search'))
    return render_template(
        'api.html',
        json="{'" + urn + "':" +
        json.dumps(TrackingData[urn], sort_keys=True, indent=4) + "}")
Пример #40
0
def get_db_memory():
    """Opens a new database connection if there is none yet for the
    current application context.
    It also initializes the database whenever it opens a connection because
    the db schema has to be uploaded for every new connection.
    This is used for the testing module.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
        with app.open_resource(os.path.join(app.root_path, '..', 'schema.sql'), mode='r') as f:
            g.sqlite_db.cursor().executescript(f.read())
            g.sqlite_db.commit()
    return g.sqlite_db
Пример #41
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        flash("Retrieving data for %s" % form.urn.data)
        with app.open_resource("static/canonical-greekLit.tracking.json","r") as f:
            TrackingData = json.loads(f.read())
        tracking_data = TrackingData[form.urn.data]
        return render_template("display.html", 
            title="Tracking information for " + form.urn.data,
            urn = form.urn.data,
            f = tracking_data)
    return render_template('search.html',
        form = form,
		title='Search')
Пример #42
0
def send_email(subject, sender, recipients, text_body, html_body, attachment=False, mimetype=None, bulk=False):
    if bulk:
        with mail.connect() as conn:
            for recipient in recipients:
                msg = Message(subject, sender=sender, recipients=[recipient])
                msg.body = text_body
                msg.html = html_body
                conn.send(msg)
    else:
        msg = Message(subject, sender=sender, recipients=recipients)
        msg.body = text_body
        msg.html = html_body
        if attachment:
            with app.open_resource(attachment) as fp:
                msg.attach(attachment[(attachment.rindex('/')+1):], mimetype, fp.read())
        mail.send(msg)
Пример #43
0
def test():
    if request.method == 'POST':
        url = request.form['url']
        email = request.form['email']
        s = Screenshot()
        s.capture(url, 'website.png')
        print url
        print email
        msg = Message("Test",
                sender=ADMINS[0],
                recipients=[email])
        msg.body=url
        with app.open_resource("../website.png") as fp:
                msg.attach("../website.png", "image/png", fp.read())
        mail.send(msg)
    return render_template('index.html', title='Home');
Пример #44
0
def display():

    with app.open_resource('static/corpus000.txt') as f:
        content = f.read()

    cap = caption.Caption(content)
    cap.make()
    cartoon = cg.Cartoon(cap)

    svg_cartoon = cartoon.assemble()

    this_cartoon = Cartoon(svg_cartoon)
    db.session.add(this_cartoon)
    db.session.commit()

    drawing_markup = Markup(svg_cartoon)

    return render_template('display.html',
        drawn=True,
        svgwrite=drawing_markup)
Пример #45
0
def init_db():  
    """Initializes the database."""
    db = get_db()
    with app.open_resource('schema.sql', mode='r') as f:
        db.cursor().executescript(f.read())
Пример #46
0
 def deploy_test_data(self):
     with closing(self.connect()) as db:
         with app.open_resource('sample.sql') as f:
             db.cursor().executescript(f.read())
         db.commit()
Пример #47
0
 def reset_codes(self):
     with closing(self.connect()) as db:
         with app.open_resource('code_val.sql') as f:
             db.cursor().executescript(f.read())
         db.commit()
Пример #48
0
def init_db():
    """call it only you want to reset the db"""
    with closing(connect_db()) as db:
        with app.open_resource('FRAPI.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Пример #49
0
	def db_initialise_empty(self):
		with app.app_context():
			db = self.db_get()
			with app.open_resource(os.path.join('db', 'schema.sql'), mode='r') as f:
				db.cursor().executescript(f.read())
			db.commit()
Пример #50
0
def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Пример #51
0
def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource(os.path.join(app.root_path, '..', 'schema.sql'), mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Пример #52
0
def words(): 
	with app.open_resource("static/words.json") as f:
		data = json.load(f)
Пример #53
0
def about():
	with app.open_resource('static/text/about.txt') as data:
		data = data.read()
		data = data.decode("utf-8")
		group = json.loads(str(data))
	return render_template("about.html", group = group)
Пример #54
0
def init_db():
    db = get_db()
    with app.open_resource('module/database/schema.sql', mode='r') as f:
        db.cursor().executescript(f.read())
    db.commit()
Пример #55
0
import os

import leancloud
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler

from app import app
from cloud import engine
from sqlite import init_db


APP_ID = os.environ['LC_APP_ID']
MASTER_KEY = os.environ['LC_APP_MASTER_KEY']
PORT = int(os.environ['LC_APP_PORT'])

#init sqlite db
with app.open_resource('schema.sql', mode='r') as f:
    init_db(f)



leancloud.init(APP_ID, master_key=MASTER_KEY)

application = engine

if __name__ == '__main__':
    # 只在本地开发环境执行的代码
    app.debug = True
    server = WSGIServer(('localhost', PORT), application, handler_class=WebSocketHandler)
    server.serve_forever()
Пример #56
0
 def refresh(self):
     with closing(self.connect()) as db:
         with app.open_resource('schema.sql') as f:
             db.cursor().executescript(f.read())
         db.commit()
         db.close()
Пример #57
0
def init_db():
    with app.app_context():
        db = get_database()
        with app.open_resource(app.config['SCHEMA'], mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Пример #58
0
def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Пример #59
0
def get_resource_as_string(name, charset='utf-8'):
    with app.open_resource(name) as f:
        return f.read().decode(charset)