#--------DELETE elif request.method == 'DELETE': try: if int(shard_id) % 2 == 1: order_d = expense_5.query.filter_by(id=order_id).first() if order_d is not None: db.session.delete(order_d) db.session.commit() return json.dumps({'status': True}), 204 else: return json.dumps({'staus': False}), 404 else: order_d = expense_6.query.filter_by(id=order_id).first() if order_d is not None: db.session.delete(order_d) db.session.commit() return json.dumps({'status': True}), 204 else: return json.dumps({'staus': False}), 404 except IntegrityError: return json.dumps({'status': False}) #------------------------------------------------------------------------------------- #----run app service---- if __name__ == "__main__": HOSTNAME = 'mysqlserver' database = CreateDB(hostname=HOSTNAME) app.run(host='0.0.0.0', port=5002, debug=True)
if order: return datetime.now().hour*60 + datetime.now().minute -\ order.created.hour+order.created.minute else: return 0 @app.route('/') def score(): confirmed_orders = Orders.query.order_by(Orders.status).filter( Orders.confirmed.isnot(None)) today_confirmed_orders = [ order for order in confirmed_orders if order.confirmed.day == datetime.now().day and order.confirmed.month == datetime.now().month ] unconfirmed_order = Orders.query.order_by(Orders.created).filter( Orders.confirmed.is_(None)).first() unconf_order_waiting_time = count_waiting_time(unconfirmed_order) unconfimed_orders = Orders.query.order_by(Orders.created).filter( Orders.confirmed.is_(None)).count() return render_template( 'score.html', count_today_confirmed_orders=len(today_confirmed_orders), count_unconfirmed_orders=unconfimed_orders, unconf_order_waiting_time=int(unconf_order_waiting_time)) if __name__ == "__main__": app.run()
@app.route("/task/<task_id>", methods=["GET"]) def view(task_id): t = Task.query.get(task_id) print t return render_template("task.html", task=t) @app.route("/task/<task_id>", methods=["POST"]) def update_task(task_id): t = m.Task.query.get(task_id) t.title = request.form['title'] t.notes = request.form['notes'] m.save_all() return redirect(url_for("home")) @app.route("/task/complete/<task_id>", methods=["POST"]) def complete_task(task_id): t = m.Task.query.get(task_id) t.complete() m.save_all() return redirect(url_for("home")) @app.route("/task/delete/<task_id>", methods=["POST"]) def delete_task(task_id): t = m.Task.query.get(task_id) t.hide = True m.save_all() return redirect(url_for("home")) if __name__ == '__main__': app.run(debug=True)
#!/usr/bin/python # -*- coding: utf-8 -*- # from flask import Flask, request, jsonify, make_response, send_from_directory # from flask_sqlalchemy import SQLAlchemy # from sqlalchemy import desc # import uuid # from werkzeug.security import generate_password_hash, check_password_hash # import jwt # import datetime # from functools import wraps from model import app from game import game_api from user import user_api from kifu import kifu_api from util import util_api app.register_blueprint(user_api, url_prefix='/users') app.register_blueprint(game_api, url_prefix='/games') app.register_blueprint(kifu_api, url_prefix='/kifus') app.register_blueprint(util_api, url_prefix='/util') if __name__ == '__main__': app.run(host='0.0.0.0', debug=False, ssl_context=('cert.pem', 'privkey.pem')) # db.create_all()
def main(): app.run(host="0.0.0.0", port='80', threaded=True, debug=True)
from celery import Celery from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import Table, Column, Integer, String, Date, Float, TIMESTAMP, desc import os, sys path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'sweet/') sys.path.append(path) from model import app, db from api import api from views import views app.register_blueprint(api) app.register_blueprint(views) port = 1234 if __name__ == "__main__": #app.run(debug=True) if len(sys.argv) > 1 and sys.argv[1] == "experiment": port = 9527 if len(sys.argv) > 1 and sys.argv[1] == "production": port = 5566 if len(sys.argv) > 1 and sys.argv[1] == "development": port = 1234 port = int(os.environ.get('PORT', port)) app.run(host='0.0.0.0', port=port, debug=True)
@app.route('/shutdown', methods=['GET', 'POST']) def shutdown(): shutdown_server() return 'Server shutting down...' if __name__ == '__main__': app.debug = True # HOST = environ.get('server_host', 'localhost') HOST = environ.get('server_host', '192.168.0.105') ## NAME = environ.get('server_name','phu.co.tcb.vn:8888') # HOST = environ.get('server_host', 'localhost') try: # PORT = int(environ.get('8080', '8888')) PORT = int(environ.get('server_port', '33507')) except ValueError: PORT = 33507 app.run(HOST, PORT, threaded=True) # if __name__ == '__main__': # # Run the app on all available interfaces on port 80 which is the # # standard port for HTTP # # db.create_all() # port = int(os.environ.get("PORT", 33507)) # app.run( # host="0.0.0.0", # port=port, # )
response['data'] = "null" return jsonify(response), response['status_code'] @app.route('/firmware/hp_server/delete/serial_no/<_serial_no>', methods=['GET']) def delete_hp_server_by_serial_no(_serial_no): response={} try: print("Hello") _server = HP.query.filter_by(serial_no=_serial_no).one() print(_server) db.session.delete(_server) db.session.commit() except: e = sys.exc_info() logger.info("ERROR: Delete %s <%s>" %(_serial_no, e[:2])) response['status'] = "fail" response['status_code'] = '400' response['message'] = "Bad Request or no record found for %s" % _serial_no else: logger.info("Success: Delete %s" % _serial_no) response['status'] = "success" response['status_code'] = '200' response['data'] = "null" return jsonify(response), response['status_code'] if __name__ == '__main__': app.run(host='0.0.0.0',port=5001, debug=True) logger.info("Starting up Firmwares API Application")
@app.route("/attraction/<id>") def attraction(id): return render_template("attraction.html") @app.route("/booking") def booking(): return render_template("booking.html") @app.route("/thankyou") def thankyou(): return render_template("thankyou.html") ############################### ############# api ############# ############################### # Attractions APIs app.register_blueprint(attraction_api) # Users APIs app.register_blueprint(user_api) # Bookings APIs app.register_blueprint(booking_api) # Orders APIs app.register_blueprint(order_api) if __name__ == '__main__': app.run(port=3000, host="0.0.0.0")
there will always have 10s between all data :return: """ global last_call_time, data_getter_running print("Process load getter starts running") try: while time.time() < last_call_time + MAX_INACTIVE_LOOP_TIME: cpus = multiprocessing.cpu_count() avg = os.getloadavg()[0] / cpus now = datetime.utcnow() load = Load(time=now, value=avg) _db.session.add(load) _db.session.commit() time.sleep(10) except: print("Unexpectd error in the data getter process occured ... ") finally: data_getter_running = False data_getter_running = False print("Process load getter stops running") return if __name__ == '__main__': db.create_all() clean_db() p = Thread(target=auto_load, args=()) p.start() app.run(port=5000)
return dict(navlinks=[ ('/', 'Home'), ('/venue', 'Venue & directions'), ('/london', 'London') ]) @app.context_processor def title(): titles = { '/': 'Home', '/venue': 'Venue and Directions', '/london': 'London', '/playlist': 'Playlist', '/wedding_list': 'Wedding List' } base_path = '/%s' % request.path.lstrip('/').split('/')[0] return dict(title=titles[base_path]) app.add_url_rule('/venue', view_func=RenderTemplateView.as_view('venue_view', template_name='venue.html')) app.add_url_rule('/london', view_func=RenderTemplateView.as_view('london_view', template_name='london.html')) app.add_url_rule('/wedding_list', view_func=RenderTemplateView.as_view('wedding_list_view', template_name='wedding_list.html')); app.config['UPLOAD_FOLDER'] = os.path.abspath(os.path.join(app.root_path, 'playme')) app.secret_key = os.environ.get('FLASK_SECRET_KEY', '4FWlbReDt9AYliu2ys6bGYnuhO+DLl4zH3edeEJD6bU=') app.debug = app.config['DEBUG'] if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.debug = True app.run(host='127.0.0.1')
str(item.create_time), "taskid": item.taskid, "total": total, "percent": "100%", "title": "<a target='_blank' href=" + item.wburl + ">" + item.title + "</a>", "status": statusdic[item.status] }) except Exception as e: print e logging.error("taskinfo" + str(e)) taskinfo["code"] = 1 taskinfo["msg"] = "" taskinfo["count"] = 1000 taskinfo["data"] = [] return jsonify(taskinfo) else: taskinfo["code"] = 0 taskinfo["msg"] = "" taskinfo["count"] = 1000 return jsonify(taskinfo) if __name__ == '__main__': app.run(host="0.0.0.0", port=9999, debug=True)
db.session.add(new_user) db.session.commit() return render_template( "user/tao_moi_user.html", ) # if __name__ == '__main__': # app.debug = True # HOST = environ.get('server_host', 'localhost') # # HOST = environ.get('server_host', '192.168.0.105') # # HOST = environ.get('server_host', 'localhost') # try: # # PORT = int(environ.get('8080', '8888')) # PORT = int(environ.get('server_port', '33507')) # except ValueError: # PORT = 33507 # app.run(HOST, PORT, threaded = True) if __name__ == '__main__': # Run the app on all available interfaces on port 80 which is the # standard port for HTTP db.create_all() app.debug = True port = int(os.environ.get("PORT", 33507)) app.run( host="0.0.0.0", port=port, )
@app.route('/submit-data', methods=['POST']) def submit_data(): """Submits user data and returns an adventure.""" # Gets all fields of form data time_pref = request.form.get('time_pref') latitude = request.form.get('latitude') longitude = request.form.get('longitude') adv = adventure.Adventure(latitude, longitude, time_pref) adventah = adv.get_adventure() adv_json = json.dumps(adventah) print "Im in route now...... adventah" session['adventure'] = adv_json print "********************\n\n\n" print "\n\n This is the adventah added to the session\n\n" print adventah print "********************\n\n\n" return adv_json if __name__ == '__main__': app.debug = True connect_to_db(app) DebugToolbarExtension(app) app.run(host="0.0.0.0",port=5000)
flash('Your request has been sent. Will be process in 2 working days') return render_template('withdrawal.html', form=form) @app.route('/deposit', methods=['GET', 'POST']) @login_required def deposit(): return render_template('deposit.html') @app.route('/logout') @login_required def logout(): logout_user() flash('You have been Logged out') return redirect(url_for('login')) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 if __name__ == '__main__': app.run(debug=True, port=2342)
__author__ = 'rkourav' import flask.ext.restless from model import db, app, Profile, Blog db.create_all() manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db) manager.create_api(Profile, methods=['GET', 'POST', 'DELETE', 'PUT']) manager.create_api(Blog, methods=['GET', 'POST', 'DELETE', 'PUT'], results_per_page=15) app.run(threaded=True)
if not post_update: flash("Update was successful") return redirect(url_for('post_index')) else: error = post_update flash(error) return render_template('update.html', post=post) # DELETE @app.route('/delete/<id>', methods=['POST', 'GET']) def post_delete(id): post = Post.query.get(id) # Check if the post exists: if post is None: flash("This entry does not exist in the database") return redirect(url_for(post_index)) post_delete = post.delete(post) if not post_delete: flash("Post was deleted successfully") else: error = post_delete flash(error) return redirect(url_for('post_index')) if __name__ == '__main__': app.debug = True app.run()
post.title = post.title if text: post.text = text else: post.text = post.text if photo: post.photo = photo else: post.photo = post.photo db.session.commit() return redirect('/display_posts') if __name__ == "__main__": app.run() # make sure templates, etc. are not cached in debug mode # app.jinja_env.auto_reload = app.debug # connect_to_db(app) connect_to_db(app) # Use the DebugToolbar DebugToolbarExtension(app) app.run(host="0.0.0.0")
@app.route('/database/crops', methods=['POST']) def update_crops(): Name = request.json.get('Name') water_requirement = request.json.get('waterrequirement') seedrequirement = request.json.get('seedrequirement') humanrequirement = request.json.get('humanrequirement') plantperarea = request.json.get('plantperarea') rootdepth_seedling = request.json.get('rootdepth_seedling') rootdepth_vegetative = request.json.get('rootdepth_vegetative') rootdepth_flowing = request.json.get('rootdepth_flowing') crop = Crops(Name=Name, water_requirement=water_requirement, seedrequirement=seedrequirement, humanrequirement=humanrequirement, plantperarea=plantperarea, rootdepth_flowing=rootdepth_flowing, rootdepth_seedling=rootdepth_seedling, rootdepth_vegetative=rootdepth_vegetative) db.session.add(crop) db.session.commit() return Crops_Schema.jsonify(crop) #Run Server if __name__ == '__main__': db.create_all() app.run(host='0.0.0.0', port='5000', debug=True)
@login_required def show_followed(): resp = make_response(redirect(url_for('home'))) resp.set_cookie('show_followed', '1', max_age=30 * 24 * 60 * 60) return resp @app.route('/confirm') @login_required def resend_confirmation(): token = current_user.generate_confirmation_token() send_email(current_user.email, 'Confirm Your Account', 'confirm', user=user, token=token) flash('A new confirmation email has been sent to you by email') return redirect(url_for('home')) @app.route("/") @login_required def logout(): logout_user() flash('You have been logged out') return redirect(url_for("login")) if __name__ == '__main__': app.run(debug=True, port=5529)
# url routing @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 @app.after_request def shutdown_session(response): db.session.remove() return response @app.route('/') def hello_world(): return "Hello World!" @app.route('/users/') def list_players(): players = Player.query.all() a = "xxx"; d = {} for p in players: app.logger.debug(p.username) a = a + " " + p.username return "Hello Players: %s " % (a) if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0')
return render_template('index.html') @app.route('/topten/<cmd>') def TopTenHandler(cmd): if cmd == 'update': topten.update() return 'top 10 updated successfully' @app.route('/pattern', methods = ['GET', 'POST']) def PatternHandler(): if request.method == 'GET': return render_template('pattern.html') else: i = request.form['input'] o = request.form['output'] pattern.updatePattern(i, o) return '' @app.route('/pattern/<input>') def PatternLookup(input): return pattern.getOutputByInput(input) @app.route('/activity/<cmd>') def ActivityHandler(cmd): if cmd == 'update': activity.update() return 'activity updated successfully' if __name__ == '__main__': app.run(host = SERVER_HOST, port = SERVER_PORT, debug = True)
# db.session.add(user) # db.session.commit() # flash('User successfully registered') # return redirect(url_for('login')) email = str(request.form.get["email"]) pw1 = str(request.form.get["password"]) pw2 = str(request.form.get["password2"]) if not pw1 == pw2: return redirect(url_for("home")) if DB.get_user(email): return redirect(url_for("home")) salt = PH.get_salt() hashed = PH.get_hash(pw1 + salt) DB.add_user(email, salt, hashed) return redirect(url_for("home")) ''' @login_manager.user_loader def load_user(user_id): return User.query.filter(User.id==user_id) app.secret_key = '0ZyLk/0K1+GVdZTRWCfK441+CUHGmRKXzly1UXnws29VOYHuVTCyhFfMh4c9OcWUgL8iGgk5a99t9T1Xo5EsC9wmoTAiDPZu8US' if __name__ == '__main__': app.run(port=5000, debug=True, host='0.0.0.0')
filename = secure_filename(file.filename) #path to file path = app.config['UPLOAD_FOLDER'] + '/' + filename file.save(path) project = Projects.query.filter_by(id=project_id).first() project.user_stories = path db.session.add(project) db.session.commit() return jsonify({ 'message': 'file successfully uploaded!', 'status_code': '201' }) else: abort(400, message="file type not allowed") # Endpoints api.add_resource(Welcome, '/') api.add_resource(Create_user, '/users/register') api.add_resource(Auth, '/users/auth') api.add_resource(Project_crud, '/projects/<project_id>') api.add_resource(Project, '/projects') api.add_resource(All_actions, '/actions') api.add_resource(Single_action, '/actions/<action_id>') api.add_resource(Action, '/projects/<project_id>/actions') api.add_resource(Action_crud, '/projects/<project_id>/actions/<action_id>') api.add_resource(Upload_files, '/projects/<project_id>/upload') if __name__ == '__main__': app.run(debug=True)
"partner_aZcyTJgv4q9y0g1ebtdzPmTUQk4vZYgml4SlbD1TDfPO1r94qkVKOiDQ", "filters": { "bank_transaction_id": orderNumber } } headers = { 'content-type': 'application/json', 'x-api-key': 'partner_aZcyTJgv4q9y0g1ebtdzPmTUQk4vZYgml4SlbD1TDfPO1r94qkVKOiDQ' } find_order = requests.post(url, data=json.dumps(payload), headers=headers) find_data = json.loads(find_order.text) find_result = find_data['trade_records'][0]['record_status'] return jsonify(last_thank_you(number, data, find_result)) else: return jsonify(sever_error) else: login_error = { "login_error": True, } return jsonify(login_error) if __name__ == '__main__': # app.run(port=3001,debug=True) app.run(host="0.0.0.0", port=3000)
results=pagination_results, form=search, page=page, per_page=per_page, pagination=pagination) return render_template("results.htm", form=search, results=[], page=page, per_page=per_page, pagination=pagination) # form = CreateEntryForm(request.form) # if request.method == 'POST' and form.validate(): # info = User(form.location.data, form.age.data, form.symptoms.data, # form.ip_address.data, form.travel_history.data) # db.session.add(info) # db.session.commit() # flash('Entry successfully created.') # return redirect(url_for('index')) # return render_template('create_entry.htm', form=form) # @app.route('/static/resources.htm') # def get_resources(): # return if __name__ == "__main__": app.run(port=80, host='0.0.0.0')
checklist22 = set(checklist2) checklist22 = list(checklist22) dictionary = [u.__dict__ for u in db.session.query(lyricModel).all()] for i in dictionary: del i['_sa_instance_state'] df = pd.DataFrame(dictionary) word = request.form.get('Rhyme-Word') dfFiltered = df.loc[df['lyrics'].str.split().str[-1].isin(pronouncing.rhymes(word))] dfJSON = dfFiltered.to_json(orient='index') numberSyllable = int(request.form.to_dict().get('syllables-num')) return render_template('result.html', number=str(numberSyllable), checklist2=checklist22, checklist3=checklist3, dfJSON=dfJSON, word=word) return render_template('main.html') @app.route('/reset', methods=['GET', 'POST']) def reset(): usage = lyricModel.query.filter_by(usage=1).all() for i in usage: i.usage = 0 try: db.session.commit() except: pass return redirect(url_for('main')) if __name__ == "__main__": app.secret_key = '123456' app.run(debug='Enable', use_reloader=True)
@app.route('/sale-profit-linechart.json') def show_sale_profit_chart(): """Return sale profit data as json.""" user_id = session.get("user_id") month_num = int(request.args.get("months")) attr_list = ['gap', 'nike'] data_dict = show_sal_profitchart_json(user_id, month_num, attr_list) return jsonify(data_dict) ########################################################################### if __name__ == "__main__": # We have to set debug=True here, since it has to be True at the # point that we invoke the DebugToolbarExtension app.debug = False app.jinja_env.auto_reload = app.debug # make sure templates, etc. are not cached in debug mode connect_to_db(app) # Use the DebugToolbar # DebugToolbarExtension(app) app.run(port=5000, host='0.0.0.0')
def main(): init_db() app.run()
@app.route('/add_training/' , methods=['POST', 'GET']) def training_add(): if request.method == 'POST': data=json.loads(request.get_json()) red_c_gs=data['red_c_gs'] green_c_gs=data['green_c_gs'] blue_c_gs=data['blue_c_gs'] color_c=data['color_c'] background_type=data['background_type'] num_layers=data['num_layers'] t=training(red_c_gs,green_c_gs,blue_c_gs,color_c,background_type,num_layers) q=t.add(t) return("hi") else: return("no") if __name__ == '__main__': app.debug = True port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
'apikey': api_key }) return jsonify({'msg': _ERROR.get(response.get('code'))}, 409) @app.route('/upload', methods=['POST']) def uploaded_file(): ip = request.remote_addr response = controller.guard() if not response.get('status'): return jsonify({'msg': ERROR[response.get('code')]}, 401) if 'log' not in request.files: return jsonify({'msg': ERROR.get(4)}, 400) file = request.files['log'] path_absolute = os.path.join(app.config['UPLOAD_FOLDER'], file.filename) if os.path.isfile(path_absolute): return jsonify({'msg': ERROR.get(5)}, 409) file.save(path_absolute) threading.Thread(target=controller.save, args=(path_absolute, ip, conn)).start() return jsonify({'msg': 'sent with success'}, 200) if __name__ == '__main__': app.run(host=HOST, port=PORT, debug=True)