def main(): """Main runner function""" sqlite_db = Path(__file__).parent / "site.db" if not os.path.isfile(sqlite_db): # Seeds datbase if empty seed_database() # Run Flask app app.run(debug=True)
def run(): """ Run app """ print( "=======================================================================\n" "================================ start ================================\n" "=======================================================================" ) app.run(port=8000, debug=True)
def start_bot_weebook_ngrok(): bot.remove_webhook() ngrok_conn = ngrok.connect(port) http_url = ngrok_conn.public_url https_url = http_url.replace('http://', 'https://') bot.set_webhook(url=https_url + '/' + secret) print( f'------------- ONLY FOR TESTS (USING Webhook and pyngrok) -------------\n' f'http_url = {http_url}\nhttps_url={https_url}\n') app.run(debug=True)
def start_bot(): if global_settings.DEBUG == True: bot.polling() else: import time print('STARTED') bot.remove_webhook() time.sleep(1) bot.set_webhook( url=WEBHOOK_URL, certificate=open('nginx-selfsigned.crt', 'r') ) app.run(host='127.0.0.1', port=5000, debug=True)
time = user.filter(or_(Event.start.between(str(new_date), str(end_date))), Event.end.between(str(new_date), str(end_date))) results = [] for x in time.all(): result = {} result["id"] = x.id result["description"] = x.description result["start"] = x.start.isoformat() result["end"] = x.end.isoformat() results.append(result) return results @app.route('/', methods=["POST"]) def handle(): result = rpc(request.json) return jsonify(result) @app.route('/create', methods=["POST"]) def create(): if request.json["secret"] == SECRET: db.create_all() return jsonify("Successful") if __name__ == "__main__": rpc['Timetable.add'] = timetable_add rpc['Timetable.get'] = timetable_get app.run(host='0.0.0.0', port=PORT)
if request.method == "GET" and form.search.data and form.validate: search = form.search.data excluded_terms = [ ' & !' + term for term in form.excluded.data.split()][::-1] exclusions = "".join(excluded_terms) if form.include_body.data: column_name = 'body_tsv' else: column_name = 'title_tsv' conn = engine.connect() query = ("SELECT * FROM post WHERE %s @@ to_tsquery('''%s''%s') " + "AND timestamp > current_timestamp - interval '31 days' " + "ORDER BY timestamp DESC;") % \ (column_name, search, exclusions) result = conn.execute(query) for post in result.fetchall(): post = dict(zip(post.keys(), post.values())) posts.append(post) return render_template('index.html', form=form, posts=posts) if __name__ == '__main__': # Base.metadata.create_all(bind=engine) app.run(host='0.0.0.0', port=9020)
from config import app """ @TODO 1) Создать связь один ко многим в моделе Attendance 2) Создать запросы в apps.attendance.controller для создания, удаления и редактирования Attendance 3) Создать html формы для User, Attendance """ if __name__ == '__main__': app.run(host='localhost', port=5000)
import os from config import app from flask_restful import Api from src.services.task_service import TaskList, TaskService api = Api(app) api.add_resource(TaskList, '/v1/tasks/') api.add_resource(TaskService, '/v1/tasks/<task_id>') if __name__ == '__main__': port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
def createTables(): msg = None stat = None try: logger.warn("CREATING TABLES") db.create_all() msg = "Non existent tables created!" stat = Result.SUCCESS except Exception as ex: msg = str(ex) stat = Result.FAILURE return Result(data=msg, status=stat).toJSON() if __name__ == "__main__": app.config["SQLALCHEMY_DATABASE_URI"] = \ config.getAppConfig("SQLALCHEMY_DATABASE_URI")\ .format(environ.get("MASK_CREDENTIALS", "root:root")) print(config.getAppConfig("SQLALCHEMY_DATABASE_URI")) useDebug = config.getLandscape() == "sandbox" usePort = 5000 if useDebug else None config.setupLogger() print("\n" * 2) logging.warning('=== Launching 3DMask Web API ({}) ===' .format(config.getLandscape())) app.run(debug=useDebug, use_reloader=True, port=usePort, host="0.0.0.0")
form = VideoForm(request.form) form.title.data = data.title form.link.data = data.link if request.method == 'POST' and form.validate(): data.title = request.form["title"] data.link = request.form["link"] db.session.commit() flash("Video updated!", "success") return redirect(url_for('dashboard')) return render_template('edit_video.html', form=form) # TODO: Delete Video @app.route('/delete_video/<int:id>', methods=['GET', 'POST']) @login_required def delete_video(id): data = Videos.query.get(id) if data: db.session.delete(data) db.session.commit() msg = "Video deleted!" return render_template('dashboard.html', msg=msg) else: error = "Video was not deleted!" return render_template('dashboard.html', error=error) app.wsgi_app = ProxyFix(app.wsgi_app) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
classname=classname) @app.route("/api/classroom/attendence", methods=["POST"]) def post_attendence(): enum_presence = request.form["presence"] new_data = { "classcode": request.form["classcode"], "classname": request.form["classname"], "student_name": request.form["student_name"], "student_id": int(request.form["student_id"]), "date": parser.parse(request.form["date"]), "presence": PresenceEnum(enum_presence) } classroom = Classroom(**new_data) db.session.add(classroom) db.session.commit() return "OK" @app.route("/api/classroom", methods=["GET"]) def classroom_list(): result = Classroom.query.all() return jsonify(all_classroom_schema.dump(result)) if __name__ == "__main__": if not os.path.exists(database_file): db.create_all() app.run(host="0.0.0.0", port=12301, debug=True)
def run(host, port): app.run(host=host, port=int(port), debug=False)
raise APIError("Unable to create expense with data: {}".format(request.json), payload=dict(status="error", error=expense)) @app.route(URL_BASE + 'expenses/<_id>/', methods=['GET', 'PUT', 'DELETE']) def single_expense(_id): """ Single expenses endpoint""" if request.method == "GET": expense = get_single_expense(_id) if expense: return jsonify({"status": "ok", "data": expense}) else: raise APIError("Unable to retrieve expense '{}'".format(_id), payload=dict(status="error"), status_code=404) elif request.method == "PUT": updated = update_expense(_id, request.json) if updated: return jsonify({"status": "ok", "message": "Expense '{}' updated correctly with new values: {}" .format(_id, request.json)}) else: raise APIError("Error updating expense '{}'".format(_id), payload=dict(status="error")) elif request.method == "DELETE": deleted = delete_expense(_id) if deleted: return jsonify({"status": "ok", "message": "User '{}' deleted correctly".format(_id)}) else: raise APIError("Error deleting user '{}'".format(_id), payload=dict(status="error")) if __name__ == "__main__": app.run(debug=True, host='0.0.0.0')
width = 0.8 axis.bar(xs, ys, width) canvas = FigureCanvas(fig) output = StringIO.StringIO() canvas.print_png(output) response = make_response(output.getvalue()) response.mimetype = "image/png" return response @app.route("/tweet_count", methods=["GET"]) def get_tweet(): queue = [tweets.s("tweets_{}.txt".format(i)) for i in xrange(0, 20)] g = group(queue) res = g() while res.ready() == "False": time.slee(3) dicts = res.get() counter = Counter() for dic in dicts: counter.update(dic) return jsonify(dict(counter)) if __name__ == "__main__": app.run(host="0.0.0.0", debug=True)
from config.persistent_config import setup_logging as pc_setup_logging def get_logger(): return logging.getLogger(__name__) if __name__ == "__main__": args = docopt.docopt(__doc__) formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s:%(message)s') logging_handler = logging.handlers.RotatingFileHandler(args["<logfile>"], maxBytes=1024*1024, backupCount=3) logging_handler.setFormatter(formatter) if args["--debug"]: logging.basicConfig(level=logging.INFO) else: logging.basicConfig(level=logging.DEBUG) get_logger().addHandler(logging_handler) api_setup_logging(logging_handler) pc_setup_logging(logging_handler) port = int(os.getenv("RGBLAMP_CONFIG_PORT")) if args['--public']: app.run(host='0.0.0.0', port=port, debug=True) else: app.run(debug=True)
# ---------------------------------------------------------------------------- @app.before_first_request def init(): red.delete('published-problems') red.set('chat-count', 0) # red.flushdb() # ---------------------------------------------------------------------------- @auth.after_login def init_user(): logged_in_user = auth.get_logged_in_user() user_record = StudentRecord(logged_in_user.id) user_record.username = logged_in_user.username if logged_in_user.role == 'teacher': user_record.open_board = True user_record.is_teacher = True user_record.save() # ---------------------------------------------------------------------------- app.register_blueprint(sse) app.register_blueprint(sandbox) app.register_blueprint(user) app.register_blueprint(problem) if __name__ == "__main__": app.run(port=8000)
from config import app from views import * from forms import * from config import app, mongo_db as db, admin app.config.from_object("config.DevelopmentConfig") print "Config init...%s" % db if __name__ == "__main__": # Add views admin.add_view(DataTypeView(db.data_type, "DataType")) admin.add_view(ModuleView(db.module, "Module")) admin.add_view(ModuleFormView(db.module_form, "Module Form")) admin.add_view(UserView(db.user, "User")) admin.add_view(TweetView(db.tweet, "Tweets")) # admin.add_view(GenerateFormView(db.module_form, 'Generate form')) # Start app app.debug = True app.run("0.0.0.0", 8000)
from app import api, UserRegister, LoginApi, StudentList, StudentDetails from config import app api.add_resource(UserRegister, '/user/signup/') api.add_resource(LoginApi, '/user/login/') api.add_resource(StudentList, '/user/get/') api.add_resource(StudentDetails, '/user/get/<int:id>') if __name__ == "__main__": app.run(debug=True, port=5555)
manager.create_api( Ballance, preprocessors={ 'POST': [ auth, preprocessor_check_adm, date_now ], 'GET_MANY': [ auth, preprocessor_check_adm ], 'GET_SINGLE': [auth, preprocessor_check_adm], 'PATCH_SINGLE': [ auth, preprocessor_check_adm ], 'DELETE_SINGLE': [auth, preprocessor_check_adm], }, postprocessors={ 'POST': [add_user_balance] }, methods=['POST', 'GET', 'PATCH', 'DELETE'], results_per_page=100, ) # start the flask loop app.debug = True app.run('0.0.0.0', 5000)
else: return 'algo no esta bien', 500 return 'listo', 200 """render_template('SU Exportaciones.html', una_lista=['Tipo ZAP Academy', 'Tipo Apoyo a Mujeres', 'Tipo Jalisco te Reconoce', 'Otro Tipo'], backup_file=backup_file, now=time.strftime("%Y%m%d-%H%M%S"))""" @roles_required('ADMINISTRADOR') @app.route("/exports", methods=['GET', 'POST']) def exports(): exportfile = export(request.args['filename']) return send_file(exportfile, as_attachment=True) @roles_required('ADMINISTRADOR') @app.route("/backup", methods=['GET', 'POST']) def backup(): # file = respaldo() return send_file('zapiensa_project_v2.db', attachment_filename='zapiensa_project_v2' + time.strftime("-%Y%m%d-%H%M%S") + '.db', as_attachment=True) if __name__ == '__main__': app.run(debug=True, port='5003')
import os from config import app from flask import Flask # APPLICATION MAIN if __name__ == '__main__': port = int(os.environ.get("PORT", 5000)) app.run('127.0.0.1', port=port) print '\nApplication Started'
return '<h1>Request failed!</h1>' @app.route('/authorize', methods=['POST']) def authorize(): try: action = request.headers['operation'] print("action.....", action) token = request.headers['X_ACCESS_TOKEN'] print("token.....", token) decoded_token = jwt.decode(token, app.config['SECRET_KEY'], algorithms="HS256") data = database.validatePermission(action, decoded_token['role']) if data: return data return None except Exception as e: return make_response( jsonify({ "title": "Error occcured", "status": HTTPStatus.BAD_REQUEST, }), HTTPStatus.BAD_REQUEST) if __name__ == "__main__": app.run(host='0.0.0.0', port=5002, debug=True)
dev.save() if ep == "log": pass # TODO : handle changes # logger.info("Topic : {0}, Message : {1}".format(*[msg.topic, msg.payload])) if __name__ == '__main__': logger = logging.getLogger('werkzeug') handler = logging.FileHandler('access.log') logger.addHandler(handler) mqtt_thread = None client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("188.166.40.162", 1883, 60) try: mqtt_thread = MQTT_Thread() mqtt_thread.daemon = True mqtt_thread.start() except Exception, e: client.disconnect() client.reconnect() logger.error(format(str(e))) app.run(host="0.0.0.0", port=5000, debug=True)
cursor.execute("UPDATE users SET confirmed='1' WHERE email=%s", (email)) conn.commit() return render_template("activated.html") cursor.close() conn.close() @app.route('/getzone') def json_blob(): address = request.args['address'] govturl = "http://maps.kamloops.ca/arcgis3/rest/services/BCDevExchange/GarbagePickup/MapServer/3/query" payload = {"geometryType":"esriGeometryEnvelope", "where":"ADDRESS = '" + address + "'", "spatialRel":"esriSpatialRelIntersects", "outFields":"Address, Zone", "returnGeometry":"true", "returnIdsOnly":"false", "returnCountOnly":"false", "returnZ":"false", "returnM":"false", "returnCountOnly":"false", "f":"pjson", "returnDistinctValues":"false"} r = requests.get(govturl, params=payload) jsonblob = r.text jdict = json.loads(jsonblob) zone = jdict["features"][0]["attributes"]["ZONE"] return zone if __name__ == "__main__": app.run(host="0.0.0.0")
file = request.files['file'] if file.filename == '': return render_template( 'error.html', message='Empty filenames are not allowed!!!' ) # returns error template if filename is empty. if file and allowed_file(file.filename): filename = secure_filename( file.filename ) # To avoid dangerous filename such as .bashrc etc. file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('display_uploaded', filename=filename)) else: return render_template('fileupload.html') except Exception as e: return render_template('error.html', message=repr(e)) @app.route('/uploads/<filename>') def display_uploaded(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) # To display uploaded file on server. if __name__ == '__main__': app.run(host=HOST, port=PORT)
hosted_by = request.args.get('hosted_by') duration = request.args.get('duration') max_marks = request.args.get('max_marks') topic = Topic.query.get(topic_id) questions = Question.query.filter_by(topic_id=topic_id, status=0) return render_template("quiz.html", questions=questions, topic=topic, hosted_by=hosted_by, duration=duration, max_marks=max_marks) @app.route('/create') def drop_all(): db.drop_all() db.create_all() return redirect(url_for('startquiz')) @app.route('/drop') def create_all(): db.drop_all() return redirect(url_for('startquiz')) if __name__ == "__main__": app.run(debug=True, port=5000) socketio.run(app)
from config import app import routes app.run(port=5000)
matches.create_table() matches.create_init_matches() matchstatistics.create_table() matchstatistics.create_init_matchstatistics() playerstatistics.create_table() playerstatistics.create_init_playerstatistics() app.storeTM = StoreTM(app.config['dsn']) app.storeTM.createTable(app.config['dsn']) app.storeTM.createInitTMs(app.config['dsn']) return render_template('home.html') @app.route('/') def home(): now = datetime.datetime.now() return render_template('home.html', current_time=now.ctime()) if __name__ == '__main__': PORT = int(os.getenv('VCAP_APP_PORT', '5000')) VCAP_SERVICES = os.getenv('VCAP_SERVICES') if VCAP_SERVICES is not None: app.config['dsn'] = get_elephantsql_dsn(VCAP_SERVICES) else: app.config['dsn'] = """user='******' password='******' host='localhost' port=54321 dbname='itucsdb'""" app.run(host='0.0.0.0', port=int(PORT))
download = Backend(result) download.start() return redirect('/') @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['file'] f.save(parameter["dir_download"]+"/"+secure_filename(f.filename)) return redirect('/') @app.route('/info') def debug_msg(): file = parameter["dir_log"]+"/log.json" with open(file) as data: data = data.read() data = json.loads(data) filesize = lambda file : (os.path.getsize(file)*10485>>20)/10000.0 if os.path.exists(file) else 0 for d in data: d['size'] = "{} MB".format(filesize(d['file'])) d['file'] = d['file'].split('/')[-1] return render_template('record.html', records=data, colnames=['file','start_time','finish_time','size']) if __name__=="__main__": with open("config/config.json") as param: param = param.read() parameter = json.loads(param) app.run(host=parameter["ip"], port=parameter["port"], debug=True)
# -*- coding: utf-8 -*- from config import app_host, app_port, app from api.wnotify import * from api.wclick import * if __name__ == '__main__': app.run(host=app_host, port=int(app_port))
), post ) flash('successfully unfollow the account') return redirect( url_for( 'index', userID=request.form['unfollowUserID'] ) ) else: error = "Failed to unfollow" flash(error) else: error = "Please choose who you want to unfollow" flash(error) return redirect(url_for('index', error="Unfollow Error")) # debugging part of the web application when internal error server happen if not app.debug: import logging from logging import FileHandler file_handler = FileHandler('log.txt') file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) # run the program if __name__ == '__main__': app.run(host='0.0.0.0', port=8080) # debug=True, ssl_context=context, threaded=True)
app.logger.error(e) abort(500) @app.route('/debts/{debt_id}', methods=['DELETE']) @facebook_auth def delete(debt_id): debt = Debt.query.get(debt_id) if debt == None: abort(404) if not (debt.debtor == g.user or debt.lender == g.user): abort(403) debt.archived = True db.session.commit() return "success" @app.errorhandler(404) @app.errorhandler(500) def fail(error): print error colours = {404: "#036", 500: "#900"} colour = colours.get(error.code, "#000") return render_template('error.html', error=error.code, colour=colour), error.code if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port=80)
db.session.add(new_item) db.session.commit() return '导入成功!' @app.route("/topics") def topics(): field_topics = [] fields = db.session.query(Field) for field in fields: field_name = field.fieldName topics = db.session.query(Topic).filter_by(field=field) topic_names = [] for topic in topics: topic_names.append(topic.topicName) field_topics.append({'field_name': field_name, 'topics': topic_names}) return render_template('propagate/topics.html',field_topics = field_topics) @app.route("/hot_status") def hot_status(): statuses = db.session.query(HotStatus).order_by(HotStatus.repostsCount.desc()).limit(100) status_hot = [] for status in statuses: uid = status.uid user = get_user(uid) status_hot.append({'status': status, 'user': user}) return render_template('propagate/hot_status.html',status_hot = status_hot) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True, port=9005)
class Data_Request(Resource): @ns1.expect(query_data_parser) def get(self): return Currency_UPD.curr_crawler(self), { 'Access-Control-Allow-Origin': '*' } @ns2.route('/') class Data_Request(Resource): @ns2.expect(query_data_parser) def get(self): return Currency_UPD.curr_list(self) @ns3.route('/') class Data_Core(Resource): def get(self): return CoreMan.list(self), {'Access-Control-Allow-Origin': '*'} @ns3.expect(core_store) def post(self): return CoreMan.insert(self), {'Access-Control-Allow-Origin': '*'} ### Main app!!! if __name__ == '__main__': app.run(host='0.0.0.0', port=6969) ############################################# # EoF
#plt.ylabel = "Counts" canvas = FigureCanvas(fig) output =StringIO.StringIO() canvas.print_png(output) response = make_response(output.getvalue()) response.mimetype = 'image/png' return response @app.route("/tweet_count", methods=['GET']) def get_tweet(): queue=[tweets.s("tweets_{}.txt".format(i)) for i in xrange(0,20)] g = group(queue) res = g() while res.ready()=="False": time.slee(3) dicts = res.get() counter = Counter() for dic in dicts: counter.update(dic) # open('values.txt','a').write(json.dumps(dict(counter))) return jsonify(dict(counter)) if __name__=='__main__': app.run(host='0.0.0.0',debug=True)
return respone cursor.close() conn.close() except Exception as e: # print(e) message = { 'status': 500, 'message': 'error in method', } print(message) respone = jsonify(message) respone.status_code = 500 return respone finally: print("finished") @app.errorhandler(404) def not_found(error=None): message = { 'status': 404, 'message': 'Record not found: ' + request.url, } respone = jsonify(message) respone.status_code = 404 return respone if __name__ == "__main__": app.run(debug=True, host="192.168.43.19")
return 'created tables' @app.route('/user') def get_user(): users = [user.serialize() for user in User.query.all()] return jsonify(users=users) @login_manager.user_loader def load_user(id): return User.query.get(id) @app.errorhandler(403) def user_not_authenticated(error): return "user is not authenticated" def auth_func(**kw): if not current_user.is_authenticated(): #abort(403) pass pre_auth_both = dict(GET_MANY=[auth_func], GET_SINGLE=[auth_func], POST=[auth_func]) pre_auth_post = dict(POST=[auth_func]) api_manager.create_api(Ad, methods=['GET', 'POST'], preprocessors=pre_auth_post, results_per_page=30) api_manager.create_api(User, methods=['GET', 'POST'], preprocessors=pre_auth_post) api_manager.create_api(Bid, methods=['GET', 'POST'], preprocessors=pre_auth_both, results_per_page=None) api_manager.create_api(Message, methods=['GET', 'POST'], preprocessors=pre_auth_both, results_per_page=None) if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=False)
@app.route('/<page>',defaults={'directory':None}) @app.route('/<path:directory>/',defaults={'page':'index'}) @app.route('/<path:directory>/<page>') def show(directory,page): if not directory: filename = page + '.html' if os.path.isfile('templates/' + filename): return render_template(filename, active='home') print filename return render_template('404.html'), 404 try: prev = directory.split('/')[-1] except: prev = None filename = directory + "/" + page + '.html' if os.path.isfile('templates/' + filename): return render_template(filename, active=page, previous=prev) print filename return render_template('404.html'), 404 @freezer.register_generator def custom404(): yield '/404' if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == "build": freezer.freeze() else: app.debug = True app.run(port=8080)
# vesna / man / item #api.add_resource(views.Catalog,'/api/catalog/') # show all collections #api.add_resource(CatalogCollections,'/api/catalog') # show segments from actvie collection if no specific collections is provided api.add_resource(catalog.Rating,'/api/rate/<string:id>/<string:rating>') api.add_resource(catalog.CatalogCollections,'/api/catalog') api.add_resource(catalog.CatalogSegments,'/api/catalog/collection') api.add_resource(catalog.CatalogTypes,'/api/catalog/collection/<string:slug>/') api.add_resource(catalog.CatalogItems,'/api/catalog/collection/<string:segment_slug>/<string:type_slug>/') api.add_resource(catalog.CatalogItemData,'/api/catalog/collection/<string:segment_slug>/<string:type_slug>/<string:sku>/') #api.add_resource(catalog.Rating,'/api/rate/<string:id>/<string:rating>') api.add_resource(buy.SideCatalogCollections,'/api/sidecatalog') api.add_resource(buy.SideCatalogSegments, '/api/sidecatalog/collection') api.add_resource(buy.SideCatalogTypes, '/api/sidecatalog/collection/<string:slug>/') api.add_resource(buy.SideCatalogItems, '/api/sidecatalog/collection/<string:segment_slug>/<string:type_slug>/') api.add_resource(buy.SideCatalogItemData, '/api/sidecatalog/collection/<string:segment_slug>/<string:type_slug>/<string:sku>/') @login_manager.user_loader def load_user(userid): return UserItem.query.get(userid) if __name__ == '__main__': app.run(debug=True)
from config import ( app, db, cur ) @app.route('/', methods = ['GET']) @swag_from('yml/get.yml') def get_pet_resource(): cur.execute("select * from pets") pets = cur.fetchall() return jsonify(pets) @app.route('/', methods = ['PUT']) @swag_from('yml/put.yml') def update_pet_resource(): val = request.json for column in request.json.keys(): if column != 'id': sql = "update pets set {0} = '{1}' where id = {2};" .format(column, val[column], val['id']) cur.execute(sql) db.commit() return jsonify({'Success': True}) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
from config import app if __name__ == "__main__": app.run(host = '0.0.0.0', port = 5000)
#!/usr/bin/env python from flask.ext.mongoengine import MongoEngine from config import app import os app.secret_key = 'teddymonkey' # get config settings if __name__ == '__main__': app.config.from_object('config') else: app.config.from_object('heroku_config') # wrap app in mongengine db = MongoEngine(app) if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.debug = True app.run(host='0.0.0.0', port=port)
try: email = key.loads(token, salt="email-confirm-key", max_age=172800) if "'" in email or '"' in email or "(" in email or " )" in email: raise Exception if ',' in email or ";" in email or "%" in email: raise Exception except Exception as e: return str(e) try: conn = mysql.connect() cursor = conn.cursor() cursor.execute('SELECT confirmed FROM users WHERE email=%s', (email,)) data = cursor.fetchall() except Exception as e: return str(e) if str(data[0][0]) == "1": return render_template("already-confirmed.html") else: try: cursor.execute("UPDATE users SET confirmed='1' WHERE email=%s", (email,)) conn.commit() return render_template("activated.html") except Exception as e: return str(e) cursor.close() conn.close() if __name__ == "__main__": app.run(host="0.0.0.0", port=80)
shell=True) out, err = session.communicate() print(out) # to = ["*****@*****.**","*****@*****.**","*****@*****.**","*****@*****.**", "*****@*****.**","*****@*****.**","*****@*****.**"] # TEXT = "Hi This email from RPA" # SUBJECT = "Test Report" # send_email(to, ["flashreport1","flashreport2"],SUBJECT, TEXT) # print("endtime") TEXT = Text SUBJECT = Subject for emailid, textfiles in alpha.items(): print(textfiles) send_email(emailid, ("MG_FLASHREPORT.xls", "MG_F&B_SUMMARY.xls"), SUBJECT, TEXT) def run_schedule(): while 1: schedule.run_pending() time.sleep(1) api.add_resource(Test, '/test') api.add_resource(Users, '/user') if __name__ == "__main__": schedule.every().day.at("07:00").do(run_particular_hour) t = Thread(target=run_schedule) t.start() app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)
from views.year import year app.register_blueprint(year, url_prefix="/year") from views.trend import trend app.register_blueprint(trend, url_prefix="/trend") from views.admin import admin app.register_blueprint(admin, url_prefix="/admin") from views.city import city app.register_blueprint(city, url_prefix="/city") if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0') else: import logging from logging.handlers import SMTPHandler from logging import Formatter from config import ADMINS,emailAddress,emailPassword,logFile from datetime import date today = date.today().strftime("%d %m %Y") mail_handler = SMTPHandler(('smtp.gmail.com',587), emailAddress, ADMINS, 'Citizen Budget: %s' % today, credentials=(emailAddress,emailPassword), secure=())
html = """ <!doctype html> <html lang="en"> <head> <title>Just an exception handler</title> </head> <body> <h1>Just an exception handler</h1> </body> </html> """ try: v = 10 / 0 except Exception as e: logger.exception(str(e), exc_info=True) return html # @app.route("/test_endpoint", methods=["POST", "GET"]) # def test_endpoint(): # # return render_template("trial.html") if __name__ == "__main__": # app.run(debug=True) host = "0.0.0.0" logger.info(f"Starting Flamme Rouge server at: {host}") app.run(host=host)
def hangup(user_id): ''' Fired when caller hangs up the phone. ''' app.logger.info("caller " + request.form['From'] + " has hung up") return "OK" ########################### ### REST ROUTES - SMS ### ########################### @app.route('/v1/<ObjectId:user_id>/sms/', methods=['POST']) def incoming_sms(user_id): sms = { "_plivo_uuid": request.form['MessageUUID'], "_user_id": user_id, "from": request.form['From'], "to": request.form['To'], "caller_name": "", "time_received": current_time(), "body": request.form['Text'] } mongo.db.sms.insert(sms) return "OK" if __name__ == '__main__': app.run(debug=DEBUG)
'function': 'confirmAuth', 'email': email, 'senha': senha } facade = Facade(clientRequest) user = facade.serverResponse() if user['status'] == True: return render_template("app.html", user=user['data']) else: return render_template("login.html") else: return render_template("login.html") @app.route("/RDCapi", methods=['POST']) def appApi(): #Get clientRequest JSON to Dict clientRequest = request.get_json(force=True) #Send Facade facade = Facade(clientRequest) #Return Facade return jsonify( facade.serverResponse()), facade.serverResponse()['status_code'] if __name__ == '__main__': app.run(app.config['HOST'], app.config['PORT'])
return "successfull" def check_date(current): print(datetime.datetime.now, current) @app.route('/js/<path:path>') def send_js(path): return send_from_directory('js', path) @app.route('/css/<path:path>') def send_css(path): return send_from_directory('css', path) @app.route('/bower_components/<path:path>') def send_bower(path): return send_from_directory('bower_components', path) @app.route('/foundation-icons/<path:path>') def send_icons(path): return send_from_directory('foundation-icons', path) @app.route('/favicon.ico') def send_favicon(): return "none" if __name__ == '__main__': app.run(debug=True,host='0.0.0.0',port = int(os.environ.get('PORT', 5000)))
from config import app app.run(debug=True, host='127.0.0.1', port=5000)
from config import app import routes if __name__ == '__main__': app.run(debug=True,host='0.0.0.0',port=2020)
from flask import render_template, request from config import app from account.models import Post, User @app.route("/") def home(): page = request.args.get("page", 1, type=int) posts = Post.objects.paginate(page=page, per_page=3) return render_template("blog/home.html", posts=posts) @app.route("/<string:slug>") def post_detail(slug): post = Post.objects.get_or_404(slug=slug) return render_template("blog/post_detail.html", post=post) @app.route("/posts/<string:username>") def post_of_author(username): author = User.objects.get_or_404(username=username) page = request.args.get("page", 1, type=int) posts = Post.objects.filter(author=author).paginate(page=page, per_page=3) return render_template("blog/home.html", posts=posts) if __name__ == "__main__": app.run()
result=store.get_user(request.form['username'], request.form['password']) if result.role is '': error = 'Invalid Credentials. Please try again.' else: session['logged_in'] = True session['username'] = request.form['username']; if result.role == 'admin': session['admin'] = True return redirect(url_for('home_page')) else: result=store.add_user(User(0,request.form['username_r'], request.form['password_r'],1,'',request.form['name'],request.form['surname'],request.form['birthdate'])) if result=='success': session['logged_in'] = True session['username'] = request.form['username_r']; return redirect(url_for('home_page')) return render_template('login.html', error=error, current_time=now.ctime()) @app.route('/init') def init_db(): store = database_initialization() store.init_db() return redirect(url_for('home_page')) if __name__ == '__main__': VCAP_APP_PORT = os.getenv('VCAP_APP_PORT') if VCAP_APP_PORT is not None: port, debug = int(VCAP_APP_PORT), False else: port, debug = 5000, True app.run(host='0.0.0.0', port=port, debug=debug)
from config import app import routes if __name__ == "__main__": app.run(debug=True)
from config import api, app import constant import os from api.AppConfig import ApplicationConfiguration from api.Images import Images from api.Flavors import Flavors api.add_resource(ApplicationConfiguration, '/api/azure/application-configuration') api.add_resource(Images, '/api/azure/images') api.add_resource(Flavors, '/api/azure/flavors') if __name__ == '__main__': ENVIRONMENT_DEBUG = os.environ.get(constant.APP_DEBUG, True) ENVIRONMENT_HOST = os.environ.get(constant.APP_HOST, '0.0.0.0') ENVIRONMENT_PORT = os.environ.get(constant.APP_PORT, '5012') app.run(debug=ENVIRONMENT_DEBUG, host=ENVIRONMENT_HOST, port=ENVIRONMENT_PORT)
from config import app import sys sys.path.append('/home/cloudbeer/projects/zp-db-mongo') #run directly if 0: if __name__ == '__main__': app.run() #run uwsgi in nginx application = app.wsgifunc() #app.run()
try: email = key.loads(token, salt="email-confirm-key", max_age=86400) if "'" in email or '"' in email or "(" in email or " )" in email: raise Exception if ',' in email or ";" in email or "%" in email: raise Exception except Exception as e: return str(e) try: conn = mysql.connect() cursor = conn.cursor() cursor.execute('SELECT confirmed FROM users WHERE email=%s', (email,)) data = cursor.fetchall() except Exception as e: return str(e) if str(data[0][0]) == "1": return render_template("alreadyconfirmed.html") else: try: cursor.execute("UPDATE users SET confirmed='1' WHERE email=%s", (email,)) conn.commit() return render_template("activated.html") except Exception as e: return str(e) cursor.close() conn.close() if __name__ == "__main__": app.run(host="0.0.0.0", port="8085")