Example #1
0
        query_wheres.append("description LIKE %s")
        query_values.append("%" + description + "%")
    # if email is not None:
    #     query_wheres.append("email LIKE %s")
    #     query_values.append("%" + email + "%")
    # if isAcceptingStr is not None:
    #     query_wheres.append("is_accepting LIKE %s")
    #     query_values.append("%" + isAcceptingStr + "%")
    if len(query_wheres) == 0:
        abort(404)

    query_wheres_str = " and ".join(query_wheres)

    queryStr = "SELECT id, name, description, email_address, phone, is_accepting FROM healthcareservice WHERE " + query_wheres_str + " LIMIT 20;"

    db = DatabaseService()
    row_headers, matchingservices = db.execute_select_query(queryStr, query_values)
    jsondata = []
    for service in matchingservices:
        jsondata.append(dict(zip(row_headers, service)))
    jsonresult = json.dumps(jsondata)

    resp = make_response(jsonresult)
    resp.headers['Content-Type'] = "application/json"

    return resp


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port="80")
Example #2
0
@app.route('/WhatsOnCampus/events/analytics', methods=['GET'])
@jwt_required
def postedEvents():
    username = get_jwt_identity()
    user = db.session.query(Users).filter(Users.email == username).first()
    events_analytics = db.session.query(EventAnalytics).filter(
        Events.postedBy == user)

    events_analytics_dict = [
        EventAnalytics.buld_analytic_dict(analytic)
        for analytic in events_analytics
    ]
    return jsonify(Events=events_analytics_dict)


# --------------------------ANALYTICS API----------------------------------------


@app.route('/WhatsOnCampus/events/<int:eid>/view')
def viewedEvent(eid):
    event_analytic = db.session.query(EventAnalytics).filter(
        EventAnalytics.eid == eid).first()
    event_analytic.views += 1
    db.session.commit()

    return jsonify(msg='success'), 200


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)
Example #3
0
File: app.py Project: Streand/RNL
from __init__ import app
from routes import routes_blueprint

app.register_blueprint(routes_blueprint)

if __name__ == '__main__':
    app.run(host='192.168.1.105',
            port=5000,
            ssl_context=('cert.pem', 'key.pem'))
Example #4
0
from models import *

# Executes before the first request is processed.
@app.before_first_request
def before_first_request():

    # Create any database tables that don't exist yet.
    db.create_all()

    # Create the Roles "admin" and "end-user" -- unless they already exist
    user_datastore.find_or_create_role(name="admin", description="Administrator")

    # Create two Users for testing purposes -- unless they already exists.
    # In each case, use Flask-Security utility function to encrypt the password.
    encrypted_password = utils.encrypt_password("test")
    if not user_datastore.get_user("*****@*****.**"):
        user_datastore.create_user(email="*****@*****.**", password=encrypted_password)

    # Commit any database changes; the User and Roles must exist before we can add a Role to the User
    db.session.commit()

    # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the
    # Users already have these Roles.) Again, commit any database changes.
    user_datastore.add_role_to_user("*****@*****.**", "admin")
    db.session.commit()


# If running locally, listen on all IP addresses, port 8080
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int("8080"), debug=app.config["DEBUG"])
Example #5
0
from __init__ import app

if __name__ == '__main__':
	app.run(debug=True, host='0.0.0.0')
Example #6
0
#!flask/bin/python
# run.py - Calls the __init__.py function (which runs all other required code), then starts the Flask server
from __init__ import app
app.run(debug=True)
Example #7
0
from __init__ import app
import sys

if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise ValueError(
            "Please input exactly 1 argument!(Input 0 for test mode)")
    if sys.argv[1] == '0':
        TEST = True
    else:
        TEST = False

    # For test
    if TEST:
        app.debug = True
        app.run(host="127.0.0.1", port=5000)

    # On server
    else:
        app.run(host="0.0.0.0", port=80)
Example #8
0
#!/usr/bin/env python3
"""
A file to start the server
"""
from __init__ import app
import logging

logger = logging.getLogger(__name__)

if __name__ == '__main__':
    if app.config['DEBUG']:
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')
        logger.debug('Running in debug mode')
        logger.debug(app.config)
    else:
        logging.basicConfig(level=logging.INFO, format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')
        logger.info('Running in production mode')
    if (app.config.get('VENMO_CLIENT_ID', None) is None) or (app.config.get('VENMO_CLIENT_SECRET', None) is None):
        logger.warning('Venmo is not set up. Set the VENMO_CLIENT_ID and VENMO_CLIENT_SECRET keys in the config file')
    app.run(host=app.config.get('HOST', None), port=app.config.get('PORT', None), threaded=True)
Example #9
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from __init__ import app

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
Example #10
0
#!/usr/bin/env python

import os

from __init__ import app

@app.context_processor
def asset_path_context_processor():
    return {'asset_path': '/static/govuk_template/'}


app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT")))
Example #11
0
	if t and num:
		u = User.query.filter_by(token=t).first()
		if u:
			port = u.port
			x = json.loads(str(urllib2.urlopen("http://xstream.cloudapp.net:%i/tracks?album=%s"%(port,num)).read()))
			return Response(json.dumps(x),mimetype='application/json')
	abort(401)

@app.route('/token=<t>/track/url=<path:url>')
def main_track(t = None, url=None):
	if t and url:
		u = User.query.filter_by(token=t).first()
		if u:
			base = os.path.join(os.getcwd(),os.path.dirname(__file__),"temp",u.username)
			if not os.path.exists(base):
				os.mkdir(base)
			urllib.urlretrieve(url,os.path.join(base,"tmp.mp3"))
			return send_file(os.path.join(base,"tmp.mp3"))
		

	abort(401)
	


if __name__ == '__main__':
	try:
        	port = int(sys.argv[1])
    	except:
        	port = 9001
    	app.run(host='0.0.0.0', port=port, debug=True)
Example #12
0
File: app.py Project: cunjif/imgso
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import sys,os,re
rootpath = os.getcwd()
rootpath = re.findall(r'.+imgso', rootpath, flags=0)[0]
sys.path.insert(0, rootpath)

try:
    from __init__ import app
except ImportError:
    print("import __init__ module error")
    exit(-1)

if __name__ == "__main__":
    app.config.from_pyfile('conf.py')
    app.run(debug=app.config['DEBUG'],host=app.config['HOST'],port=app.config['PORT'])
from __init__ import app
app.run(host='0.0.0.0')


Example #14
0
@app.route('/filelist')
def files():
    return render_template('filelist.html')

@app.route('/bbdownload')
def download():
    shutil.make_archive("Blackboard_Files", 'zip', "Blackboard_Files")

    return send_file("Blackboard_Files.zip")


dirs = {
  "dir1": {
    "file1": "None",
    "file2": "None"
  },
  "dir2": {
    "dir3": {
      "file3": "None"
    },
    "file4": "None"
  }
}




if __name__== '__main__':
    app.run(host="0.0.0.0", port= int(os.getenv("PORT",5000)), debug=True)
Example #15
0
from __init__ import app, test_dict

from tasks import say_hello
print "starting"

@app.route('/')
def basic():
    test_dict["value"] += 1
    app.logger.debug("the basics test_var is " + str(test_dict["value"]))
    return "this is the basic test var is " + str(test_dict["value"])


@app.route('/celery_it')
def celery_it():
    say_hello.apply_async()
    return "started say hello"

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
Example #16
0
"""
This script runs the FlaskWebProject application using a development server.
"""

from os import environ
from __init__ import app

if __name__ == '__main__':
    HOST = environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    app.run(HOST, PORT)
Example #17
0
api.add_resource(Users, '/users')
api.add_resource(UserActivity, '/user/activity/<string:username>')
api.add_resource(Post, '/post/<int:_id>', '/post')
api.add_resource(Posts, '/posts')
api.add_resource(Like, '/like/<int:id_post>')
api.add_resource(Likes, '/likes')
api.add_resource(Analytics, '/analytics')
api.add_resource(NumberOfUsers, '/number_of_users')


@app.before_first_request
def create_tables():
    db.init_app(app)
    db.create_all()
    #creating initial user for testing
    if not UserModel.find_by_username('test_user'):
        start_user = UserModel('test_user', 'abcxyz')
        start_user.save_to_db()


@app.after_request
def save_request_date(response):
    if current_identity:
        current_identity.last_activity_time = datetime.datetime.now()
        db.session.commit()
    return response


if __name__ == '__main__':
    app.run(port=5000, debug=True)
Example #18
0
from __init__ import app
import mail
import views
if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0',port=5050)
Example #19
0
        cur.execute("SELECT cedula FROM usuario_web WHERE token=%s", [token])
        cedula = cur.fetchone()
        nuevo = ''
        if cedula:
            cur.execute(
                "UPDATE usuario_web SET password = %s, token = %s WHERE cedula=%s",
                [pass1, nuevo, cedula])
            conn.commit()
            flash(u"Contraseña cambiada exitósamente.")
            return render_template('index.html')
        else:
            flash(
                u"El token asignado no coincide, diríjase a OLVIDÓ SU CONTRASEÑA \n para continuar el proceso."
            )
            return render_template('index.html')
    else:
        flash(u"Contraseñas no coinciden.")
        return render_template('restablecer.html')


@app.route('/logout', methods=["GET", "POST"])
def logout():
    # remove the username from the session if it's there
    session.pop('user.id', None)
    return redirect(url_for('mainIndex'))


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)
Example #20
0
from __init__ import app

if __name__ == "__main__":
    app.run(ssl_context='adhoc')
Example #21
0
    project = environ.get('PROJECT_ID')
    location = environ.get('EMAIL_NOTIFICATION_QUEUE_LOCATION')
    email_queue = environ.get('EMAIL_NOTIFICATION_QUEUE')

    parent = client.queue_path(project, location, email_queue)

    for user in user_data:
        task = {
            'app_engine_http_request': {
                'http_method': 'POST',
                'relative_uri': '/send-email',
                'app_engine_routing': {
                    'service': 'email-notification-service'
                },
                'headers': {
                    'Content-Type': 'application/json'
                },
                'body': json.dumps({
                    'user_id': user
                }).encode()
            }
        }

        response = client.create_task(parent, task)
        print(response)


#Run Server
if __name__ == '__main__':
    app.run()
Example #22
0
    owncloud_installation_url
)
owncloud_oauth_id = os.getenv("OWNCLOUD_OAUTH_CLIENT_ID", "XY")
owncloud_oauth_secret = os.getenv("OWNCLOUD_OAUTH_CLIENT_SECRET", "ABC")

owncloud_oauth_authorize = "{}/index.php/apps/oauth2/authorize%3Fredirect_uri={}&response_type=code&client_id={}".format(
    owncloud_installation_url, owncloud_redirect_uri, owncloud_oauth_id
)

service = OAuth2Service(
    servicename="port-owncloud",
    implements=["fileStorage"],
    fileTransferMode=FileTransferMode.active,
    fileTransferArchive=FileTransferArchive.none,
    authorize_url=owncloud_oauth_authorize,
    refresh_url=owncloud_oauth_token_url,
    client_id=owncloud_oauth_id,
    client_secret=owncloud_oauth_secret,
    description={"en": "ownCloud is a suite of client–server software for creating and using file hosting services.",
                 "de": "ownCloud ist eine Suite von Client-Server-Software zur Erstellung und Nutzung von File-Hosting-Diensten."},
    displayName="ownCloud",
    infoUrl="https://owncloud.com/",
    helpUrl="https://owncloud.com/docs-guides/",
    icon="./owncloud.svg"
)
Util.register_service(service)

# set the WSGI application callable to allow using uWSGI:
# uwsgi --http :8080 -w app
app.run(port=8080, server="gevent")
Example #23
0
import config
from __init__ import app

if __name__ == '__main__':
    app.run(host='0.0.0.0',
            port=config.app_conf["server"]["port"],
            debug=False)
Example #24
0
#!flask/bin/python
from __init__ import app
app.run(debug=False)
Example #25
0
from __init__ import app

if __name__ == "__main__":
    app.run(host='0.0.0.0')
Example #26
0
from __init__ import app
from config import config_data

if __name__ == '__main__':
    app.run(host='0.0.0.0',
            port=config_data['application']["server"]["port"],
            debug=False)
Example #27
0
from __init__ import app

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)
Example #28
0
    form_columns = ['text', 'pub_date']
    list_columns = ['id', 'text', 'pub_date']


# class AdminPolls(ModelView):
#     column_display_pk = True # optional, but I like to see the IDs in the list
#     column_hide_backrefs = False
#     column_list = ('id', 'name', 'parent')
#     form_columns = ('id','tex)

admin = Admin(app,
              name="polls",
              index_view=MyAdminIndexView(),
              base_template='admin/master-extended.html',
              template_mode='bootstrap3')
admin.add_view(MyModelView(User, db.session))
admin.add_view(AdminPolls(Polls, db.session))
admin.add_view(AdminChoice(Choice, db.session))


@security.context_processor
def security_context_processor():
    return dict(admin_base_template=admin.base_template,
                admin_view=admin.index_view,
                h=helpers,
                get_url=url_for)


if __name__ == "__main__":
    app.run(debug=True, host='127.0.0.1', port='5002')
Example #29
0
from __init__ import app
if __name__ == '__main__':
    #init()
    app.run(host='0.0.0.0', port=9090, debug=True, threaded=True)
Example #30
0
    If the given user mail is already registered, then just create
    a new JWT token. Otherwise, create the new user with a new token.
    """
    request_json = request.get_json()

    user = User.query.filter_by(email=request_json.get('email')).first()

    if user is None:
        new_user = User(
            email=request_json.get('email'),
            uid=request_json.get('uid'),
            avatar=request_json.get('avatar')
        )
        db.session.add(new_user)
        db.session.commit()
        auth_token = new_user.encode_auth_token(
            new_user.id)
    else:
        auth_token = user.encode_auth_token(user.id)

    return make_response(jsonify({
        'status': 'success',
        'message': 'User has been successfully registered',
        'auth_token': auth_token.decode()
    })), 201


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8000, threaded=True)
Example #31
0
from algorithm.algorithm import app_algorithm
from api.webapi import app_api
from cruddy.app_crud import app_crud
from cruddy.app_crud_api import app_crud_api
from frontend.frontend import app_frontend
from y2022 import app_y2022

app.register_blueprint(app_starter)
app.register_blueprint(app_algorithm)
app.register_blueprint(app_api)
app.register_blueprint(app_crud)
app.register_blueprint(app_crud_api)
app.register_blueprint(app_frontend)
app.register_blueprint(app_y2022)


@app.route('/')
def index():
    return render_template("index.html")


@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template('404.html'), 404


if __name__ == "__main__":
    # runs the application on the repl development server
    app.run(debug=True, port="5222")
Example #32
0
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import sys, os, re

rootpath = os.getcwd()
rootpath = re.findall(r'.+imgso', rootpath, flags=0)[0]
sys.path.insert(0, rootpath)

try:
    from __init__ import app
except ImportError:
    print("import __init__ module error")
    exit(-1)

if __name__ == "__main__":
    app.config.from_pyfile('conf.py')
    app.run(debug=app.config['DEBUG'],
            host=app.config['HOST'],
            port=app.config['PORT'])
Example #33
0
from api_models import event_query_model, event_response_model

logging.getLogger(__name__)


# Youtube mockup API
@api.route('/events')
class YouSightsEvents(Resource):
    @api.doc(
        description=
        "Events API to get list of events from various sources including meetup and eventbrite"
    )
    @api.expect(event_query_model)
    @api.marshal_with(event_response_model)
    def post(self):
        request_info = request.json
        search_topic = request_info['keyword']
        search_lng = request_info['lng']
        search_lat = request_info['lat']
        events = get_events(search_topic, search_lat, search_lng)
        if events:
            return events
        else:
            abort(404, events)
        return jsonify(error="error while processing data")


# start server
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8080)
Example #34
0
from __init__ import app
from flask import jsonify

@app.after_request
def add_header(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

@app.route("/", methods = ['GET'])
def home():
    data = 'quick redd test'
    resp = jsonify({ 'name' : 'kenneth' })
    resp.status_code = 200
    return resp


@app.route("/kenneth")
def kenneth():
    return "Hi, Im Kenneth"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)
Example #35
0
import os
from __init__ import app
# app.run(debug = True)
app.run()

# port = int(os.environ.get(('PORT'),5000))
# app.run(host='0.0.0.0', port = port)

Example #36
0
@api.route("/database_automatic_updater_state")
class DatabaseAutomaticUpdaterState(Resource):
    @basic_auth.required
    @api.doc(description="Get the youtubeData database automatic updater state"
             )
    def get(self):
        ret_info = {"is_automatic_updater_on": is_automatic_updater_on}
        return jsonify(ret_info)


# start server
if __name__ == "__main__":
    is_automatic_updater_on = False

    sys_argv = sys.argv
    if len(sys_argv) >= 2:
        if sys_argv[1] == "--auto_update_data":
            is_automatic_updater_on = True

    if is_automatic_updater_on is True:
        print("Database Automatic Updater: On")
    else:
        print("Database Automatic Updater: Off")

    if is_automatic_updater_on is True:
        database_automatic_updater = database_update_scheduler.DatabaseUpdateScheduler(
        )
        database_automatic_updater.start()

    app.run(host="0.0.0.0", port=port)
Example #37
0
from __init__ import app

if __name__ == '__main__':
    app.run('0.0.0.0', port=443)
Example #38
0
@app.route('/')
def render_home():
    return render_template('index.html')


@app.route('/upload_image', methods=['GET', 'POST'])
def upload_image():
    if request.method == 'POST':
        if not request.form:
            return redirect(request.url)
        if not request.form['userID'] or not request.form['file']:
            return redirect(request.url)
        file_str = request.form['file']
        file_str = file_str.split('data:image/jpeg;base64,')[-1]
        rand = str(random.random()).split(".")[-1]
        filename = secure_filename(request.form['userID'] + "@" + rand +
                                   ".jpg")
        src = os.path.join(app.config["UPLOAD_IMAGE"], filename)
        if os.path.isfile(src):
            os.remove(src)
        else:
            with open(src, "wb") as outfile:
                outfile.write(base64.b64decode(file_str))
                print("save successfully!")
        return redirect('/')


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port='5000')
Example #39
0
import sys

sys.path.append("/var/www/webroot/ROOT/")

from __init__ import app as application

if __name__ == "__main__":
    application.run()
Example #40
0
def generate_token():
    print(request.form)
    user_id = request.form.get('code')
    sql = "SELECT `username` FROM `users` WHERE `userid`='{}'".format(user_id)
    insert_token_sql = \
        "UPDATE `users` SET `access_token`='{}' WHERE `userid`='{}'"
    user = db.query_all(sql.format(user_id))
    if not user:
        return_data = {
            'error': '100',
            'error_description': 'user not exists'
        }
    else:
        access_token = str(abs(hash(str(time.time())+user_id)))
        db.execute(insert_token_sql.format(access_token, user_id))
        return_data = {
            'access_token': access_token,
            'refresh_token': access_token,
            'expires_in': 30 * 24 * 60 * 60 * 1000
        }
    print(return_data)
    return Response(
        json.dumps(return_data), mimetype='application/json'
    )


if __name__ == '__main__':
    # context = ('cert.crt', 'key.key')
    # app.run(host='127.0.0.1', port=5002, ssl_context=context)
    app.run(host='127.0.0.1', port=5002)
Example #41
0
from __init__ import app

#ssl tutorial from here: https://blog.miguelgrinberg.com/post/running-your-flask-application-over-https

if __name__ == "__main__" :
	app.run(host='0.0.0.0', use_reloader=True, debug=True)
from flask import Flask
from __init__ import app

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)
Example #43
0
from __init__ import app
import routes
import models

if __name__ == '__main__':
    app.run(debug=True)
Example #44
0
# std import
import sys

# package import
from __init__ import app

if __name__ == '__main__':
    # Ok it's hugly but it's run, some day we use a real configuration system
    if len(sys.argv) < 3:
        app.debug = True
    else:
        app.debug = sys.argv[2].startswith("T")

    app.run(port=int(sys.argv[1]))