return jsonify(data) @app.route('/<int:id>') def getPlaceWithId(id): data = Tourist_Places.get_place(id) return jsonify(data) @app.route('/', methods=['POST']) def insertPlace(): requestData = request.get_json() data = Tourist_Places.add_place(requestData) return jsonify(data) @app.route('/<int:id>', methods=['DELETE']) def deletePlace(id): data = Tourist_Places.delete_place(id) return jsonify(data) @app.route('/<int:id>', methods=['PUT']) def update_placeTitle(id): requestData = request.get_json() data = Tourist_Places.update_placeTitle(id, requestData) return jsonify(data) app.run(port=5000)
return render_template('prework.html', user=current_user.name, progress=progress) @app.route('/task_landing', methods=['GET']) @login_required def task_landing(): if not current_user.is_authenticated: return redirect(url_for('login')) progress = get_progress(current_user.name) return render_template('task_landing.html', user=current_user.name, progress=progress) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True, use_reloader=True)
import flask_restless from database import app as app from database import db as db import database def initialize(): database.clearDB() db.create_all() db.session.commit() database.initDisease(50) database.initCharity(50) database.initTreatment(50) print('all tables initialized') @app.route('/') def home_page(): return '/api/disease/ -- ' + str([x.name for x in database.Disease.query.all()]) + '<br>' +\ '/api/charity/ -- ' + str([x.name for x in database.Charity.query.all()]) + '<br>' +\ '/api/treatment/ -- ' + str([x.name for x in database.Treatment.query.all()]) manager = flask_restless.APIManager(database.app, flask_sqlalchemy_db=database.db) disease_blueprint = manager.create_api(database.Disease, results_per_page = 10) charity_blueprint = manager.create_api(database.Charity, results_per_page = 10) treatment_blueprint = manager.create_api(database.Treatment, results_per_page = 10) if __name__ == '__main__': #initialize() CORS(app) # Make available to all domains app.run(host="0.0.0.0", port=80)
@app.route('/get_city/<int:city_id>') def get_city(city_id): city = {'city' : {}, 'attractions' : [], 'restaurants' : []} url = 'http://sweetspots.me/api/cities/' + str(city_id) city['city'] = requests.get(url).json() for i in range(city_id * 3 - 2, city_id * 3 + 1): attraction_url = 'http://sweetspots.me/api/attractions/' + str(i) city['attractions'].append(requests.get(attraction_url).json()) restaurant_url = 'http://sweetspots.me/api/restaurants/' + str(i) city['restaurants'].append(requests.get(restaurant_url).json()) return jsonify(city) @app.route('/unit_tests') def unit_tests(): output = subprocess.getoutput("python tests.py") return json.dumps({'output': str(output)}) #DATABASE FUNCTIONS @manager.command def create_db(): db.drop_all() create_database() @manager.command def drop_db(): db.drop_all() if __name__ == '__main__': app.run(host = "0.0.0.0", port=5000, debug = True) #manager.run()
from database import app from predict.predict_month_info import predict_month_info from predict.predict_OD_info import predict_OD_info from predict.predict_rush_hour import predict_rushhour_info from predict.predict_single_station import predict_single_station from predict.predict_week_info import predict_week_info from ControlSystem import ChangeParameter from ControlSystem import Transaction_flow_bytime @app.route("/") def hello() return "欢迎使用系统" if __name__ == "__main__": app.run(host="0.0.0.0")
@app.route('/file', methods=['POST']) def file_upload(): if 'file' not in request.files: return "ERROR : No file part", 404 file = request.files['file'] if file.filename == '': return "ERROR : No selected file", 401 if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return "File Successfully Uploaded" #request.files @app.route('/file/<filename>', methods=['DELETE']) def delete_items(filename): os.remove(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return "File Successfully Deleted" @app.errorhandler(401) @app.errorhandler(404) @app.errorhandler(500) def ma_page_erreur(error): return "Error {}".format(error.code), error.code if __name__ == "__main__": app.run()
def del_med(self, Name, Serial_number, Expiry_date, Manufacture_date): x = Medicine.query.filter_by(Name=Name).first() db.session.delete(x) db.session.commit() ## @app.route("/viewrequest") def requestphone(self, Name, Serial_number, Expiry_date, Manufacture_date): if service_request.name: Medicine.query.filter_by(Name=Name).first() class ViewAll(Resource): def get(self): med = Medicine.query.all() return [k.json() for k in med] api.add_resource( Med_call, '/addmedicine/<string:Name>/<int:Serial_number>/<string:Expiry_date>/<string:Manufacture_date>' ) api.add_resource(ViewAll, '/medicine') if __name__ == '__main__': app.run(debug='True')
if request.method == "GET": return render_template('register.html') if request.method == "POST": username = request.form.get('username') password = request.form.get('password') password2 = request.form.get('password2') print(username, password, password2) if password == password2: u = User.query.filter_by(username=username).all() if not u: # 代表当前注册的用户名不存在,可以注册 user_new = User(username, password) db.session.add(user_new) db.session.commit() return render_template('login.html') else: return "该用户名已存在" else: # 这里应前端提示两次密码输入不一致 return render_template('register.html') @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)
#!/usr/bin/env python # -*- conding: utf-8 -*- # @Author:xxx # @Time : 2021/3/27 12:50 # @File :main.py # @Software: from database import app, api from Backend.login import Login, LoanCashman, payCashman from flask_cors import CORS from Backend.logs import logger CORS(app) logger.info(app) logger.debug(app) logger.error(app) api.add_resource(Login, '/login') api.add_resource(LoanCashman, '/loan') api.add_resource(payCashman, '/repayment') if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
for p in params: kw = p[0] arg = p[1] if kw == 'min_price': raw = raw.filter(House.price >= int(arg)) elif kw == 'max_price': raw = raw.filter(House.price <= int(arg)) elif kw == 'min_bed': raw = raw.filter(House.bedrooms >= int(arg)) elif kw == 'max_bed': raw = raw.filter(House.bedrooms <= int(arg)) elif kw == 'min_bath': raw = raw.filter(House.bathrooms >= int(arg)) elif kw == 'max_bath': raw = raw.filter(House.bathrooms <= int(arg)) return jsonify({ "type": "FeatureCollection", "features": [h.geojson for h in raw.all()] }) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port = port, debug=True)
from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy from database import cadastro from database import db, app # class Retorno(db.model): # data = db.column(db.datetime(2020,8,27),nullable=True) #funções banco de dados db.session.close() db.create_all() @app.route('/') def index(): return render_template("index.html") @app.route('/main') def index2(): return render_template("main.html") app.run(debug=True, host="0.0.0.0")
from database import app import os port = int(os.environ.get("PORT", 5000)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=os.environ.get("PORT", 5000))
from api.APIHuman import * from api.APIWater import * from api.APIFish import * api = Api(app) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def index(path): return render_template("index.html") @app.route('/favicon.ico') def favicon(): return app.send_static_file('favicon.ico') # Endpoints for the API api.add_resource(FishList, "/api/fish") api.add_resource(FishID, "/api/fish/<int:id>/") api.add_resource(WaterList, "/api/water") api.add_resource(WaterID, "/api/water/<int:id>/") api.add_resource(HumanList, "/api/human") api.add_resource(HumanID, "/api/human/<int:id>/") if __name__ == "__main__": app.run(host="0.0.0.0", port=80, threaded=True, debug=True)
prev_run = Logs.query.filter(Logs.input == n).first() #check if the input was previously entered. if so, get the result from the database instead of recalculating if prev_run: resp = json.loads(prev_run.output) else: resp = fib_obj.calculate(n) resp_dump = json.dumps(resp).replace(' ', '') time2 = int(time.time() * 1000) new_log = Logs(input=n, output=resp_dump, time=time1, runtime=time2 - time1) db.session.add(new_log) db.session.commit() #when RESTFul API is used, the output is returned directly. However, when the frontend is used, above 10,000 characters #the frontend can't display the output. Instead, a url is given linking to the result. This ensures that the API could be #used as part of a bigger application smoothly, while still ensuring that users of the frontend could access results. if not is_html: return jsonify(resp) if len(resp_dump) > 10000: return jsonify({"url_response": "/long_fib/" + str(new_log.id)}) return jsonify({"response": resp}) if __name__ == "__main__": db.create_all() app.run(host='0.0.0.0', port=2224, debug=True, threaded=True)
return render_template("export_books.html", data=("book", "idk")) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('index')) @app.route("/testform", methods=['GET', 'POST']) def form(): form = LoginForm() if form.validate_on_submit(): try: user = models.User.get(models.User.username == form.username.data) except models.DoesNotExist: flash("Your username or password doesn't match") else: if check_password_hash(user.password, form.password.data): login_user(user) flash("You've been logged in!") return redirect(url_for('index')) else: flash("Your username or password doesn't match") return render_template("test_forms.html") if __name__ == '__main__': app.run(debug=True, host="10.254.25.210")
completed_at = todo["completed_at"] todoModel = Todos(user_id=user.user_id, todo_title=todo_title, todo_body=todo_body, completed=completed, completed_at=completed_at, created_at=created_at) db.session.add(todoModel) db.session.commit() return jsonify({'message': 'Saved successfully', 'todo': content}) except Exception: abort(500) else: abort(401, description="You are not allowed to visit this page") @app.errorhandler(403) def forbidden(e): e = str(e).replace("403 Forbidden:", "") return (jsonify(error=e)), 403 @app.errorhandler(400) def bad_request_handler(e): e = str(e).replace("400 Bad Request:", "") return jsonify(error=(e)), 400 if __name__ == "__main__": app.run(port=8081)
from flask import Flask, render_template, request, redirect, url_for import sqlalchemy from database import User, app, db @app.route('/', methods=['GET', 'POST']) def Main(): users = User.AllUsers() if request.method == 'POST': user = User( name=request.form['name'], email=request.form['email'], password=request.form['password'] ) user.AddUser(user) return redirect(url_for('Main')) return render_template('plantilla1.html', users=users) if __name__ == '_main__': app.run(debug=True, port=5000)
# debug on make it return not print #print(sys.exc_info()) return str(sys.exc_info()) system_error_message = sys.exc_info() finally: db.session.close() if not error: print('Hello Robot') message = 'Great You Create Your New Robot WIth name: ' + str( robot_name) message += '<br /> <br /><img width="200" height="200" src="/static/' + str( robot_image) + '">' return message else: return 'hi error' @app.route('/robot_profile/<int:robot_id>') def profile(robot_id): robot = Robot.query.filter_by(id=robot_id).first() #todos = Todo.query.order_by('id').all() api_store = getStoreByRobotId(robot_id) api_list = query_api_all(robot_id) return render_template('robot.html', robot=robot) if __name__ == '__main__': app.secret_key = 'S&Djry636qyye217773ddfJJK&(488_=-*1~!{L01}046%%^&45&&#^$^^y___' app.debug = True app.run(host='0.0.0.0', port=5000)
type=int, help="Specify the port of the server.") args = parser.parse_args() if not args.ip: args.ip = '127.0.0.1' if not args.port: args.port = 5000 set_IP(args.ip) modules = load_modules() SERVERNAME = "%s:%d" % (args.ip, args.port) WSPORT = 8001 # config app.config.update(DEBUG=False, SERVER_NAME=SERVERNAME) server = SimpleWebSocketServer('', WSPORT, WSController) _thread.start_new_thread(server.serveforever, ()) spm = StreamPortManager(10) spm.start() app.run() # ssl_context='adhoc' (add this for HTTPS) print("App run exit") spm.stop() spm.join()
username = request.form['username'] password = hashlib.md5(request.form['password'].encode()).hexdigest() if Users.query.filter_by(username=username).first(): flash('The username is already taken. Please choose another one.') return render_template('register.html', form=request.form) else: new = Users(username='******'.format(username), password='******'.format(password)) db.session.add(new) db.session.commit() flash('You are registered.') session['logged_in'] = True session['username'] = username return redirect(url_for('index')) return render_template('register.html', form=request.form) @app.route('/logout', methods=['GET', 'POST']) def logout(): session.pop('logged_in', None) flash('You are logged out.') return redirect(url_for('index')) if session['logged_in'] == False: flash('You are not even logged in yet!') return redirect(url_for('index')) if __name__ == '__main__': db.create_all() app.run(debug=True)
def Login(data): status = 0 message = "succeed" user = User.query.filter_by(username=data['username']).first() if "remember" not in data: data["remember"] = 0 if user is not None: if user.verify_password(data['password']): login_user(user, remember=data['remember']) data = {'uid': user.id, 'username': user.username} else: status = 1 message = 'wrong password' data = {} else: status = 1 message = 'user do not exit' data = {} return {'status': status, 'message': message, 'data': data} @login_required def Logout(): logout_user() return {'status': 0, 'message': 'success', 'data': {}} if __name__ == '__main__': app.run(host='0.0.0.0', port=80)
city['city'] = requests.get(url).json() for i in range(city_id * 3 - 2, city_id * 3 + 1): attraction_url = 'http://sweetspots.me/api/attractions/' + str(i) city['attractions'].append(requests.get(attraction_url).json()) restaurant_url = 'http://sweetspots.me/api/restaurants/' + str(i) city['restaurants'].append(requests.get(restaurant_url).json()) return jsonify(city) @app.route('/unit_tests') def unit_tests(): output = subprocess.getoutput("python tests.py") return json.dumps({'output': str(output)}) #DATABASE FUNCTIONS @manager.command def create_db(): db.drop_all() create_database() @manager.command def drop_db(): db.drop_all() if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True) #manager.run()
# return jsonify({'message' : 'User is Promoted'}) @app.route('/user/changepass/<username>', methods=['PUT']) @token_required def promote_user(current_user, username): user = User.query.filter_by(username=username).first() if not user: return jsonify({'message': 'No User Found'}) data = request.get_json() hashed_password = generate_password_hash(data['password'], method='sha256') user.password = hashed_password db.session.commit() return jsonify({'message': 'User is Promoted'}) @app.route('/user/<public_id>', methods=['DELETE']) @token_required def delete_user(current_user, public_id): user = User.query.filter_by(public_id=public_id).first() if not user: return jsonify({'message': 'No User Found'}) #db.session.delete(user) user.deleted = True db.session.commit() return jsonify({'message': 'User has been Deleted'}) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=6200)