#!/usr/bin/python #query = 'Fist Fight' #print(youtubeSearch(query)) from flask.ext.api import FlaskAPI from flask import jsonify, request from ytsearch import youtubeSearch #initialize server app = FlaskAPI(__name__) @app.route('/') def index(): all_args = request.args.lists() query = request.args['q'] video = youtubeSearch(query) return jsonify(video) app.run('0.0.0.0', 5000)
password = bank.decrypt(encryptedpassword) pass_hash = SHA512.new(password).hexdigest() #sub with passs hash if pass_hash != 'adjiaosdjsioadjasiodjasiodjasiod': return {'authdata': 'passwords dont match'} return {'authdata': 'the passwords match'} @app.route("/password", methods=["POST"]) def password(): if not request.json: abort(400) if not request.json.has_key('encrypted_otp') and request.json.has_key('authdata'): return {'authdata' : 'error'} if request.json['authdata'] != 'hello': return {'authdata': 'authdata corrupted'} password = bank.decrypt(encryptedpassword) #sub with passs hash if password != '123123': return {'authdata': 'otp dont match'} return {'authdata': 'the otp matches'} app.run(debug=True, port = 8003)
@application.route('/login') def login(): pass @application.route('/user/<username>') def profile(username): pass with application.test_request_context(): print(url_for('login')) # print(url_for('login', next='/')) # print(url_for('profile', username='******')) @application.route('/count') @auth.login_required def index_testing(): return {'status': 'ok'} if __name__ == "__main__": application.run( # host=application.config['HOST'], # debug=application.config['DEBUG'], # port=application.config['PORT'], ) # manager.run()
data['gif'] = giphy.search(data['search']) data.pop('search') data.pop('search_type', None) gif_file = factory.create(**data) resp = send_file(gif_file) # delete the file after it's sent # http://stackoverflow.com/questions/13344538/how-to-clean-up-temporary-file-used-with-send-file file_remover.cleanup_once_done(resp, gif_file) return resp else: return print_guide() def print_guide(): commands = {} commands['text'] = 'The text to put on the gif' commands['gif'] = 'The original gif url' commands['search'] = 'search giphy for an image' commands['search_type'] = "giphy search type, 'search' or 'translate' [search]" commands['hor_align'] = 'Horizontal alignment [center]' commands['ver_align'] = 'Vertical alignment [top]' commands['text_height'] = 'Height of text as percentage of image height [20]' commands['text_width'] = 'Maximum width of text as percentage of image width [60]' samples = [] samples.append({"text": "time for work", "gif": "http://25.media.tumblr.com/tumblr_m810e8Cbd41ql4mgjo1_500.gif"}) samples.append({"text": "hey guys", "search": "elf wave"}) return {"Command Guide": commands, "Samples": samples} if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
org_count = query('select count(shortname) from orgs', [], one=True)[0][0] ip_count = query('select count(*) from ips', [], one=True)[0][0] netblock_count = query('select count(block) from netblocks', [], one=True)[0][0] return {'total_orgs': org_count, 'total_ips': ip_count, 'total_netblocks': netblock_count} @app.route('/api/stats/<org>') def route_org_stats(org): org_id = query('select id from orgs where shortname=?', [org], one=True) if org_id is None: return {'error': "Invalid organization '{0}'".format(org)} ip_count = query('select count(*) from ips where owner=?', [org_id[0][0]]) netblock_count = query('select count(*) from netblocks where owner=?', [org_id[0][0]], one=True) return {'total_ips': ip_count[0][0], 'total_netblocks': netblock_count[0][0], 'org': org} if __name__ == '__main__': from sys import argv, exit from os import remove, path if len(argv) > 1: if argv[1] == '--init': if path.isfile('test.db'): remove('test.db') get_db().executescript(schema) print('[+] Initialized database') exit() else: print('[-] Unknown command \'{}\''.format(argv)) if not path.isfile('test.db'): print('[-] You must initialize the database by using the \'--init\' option') exit() app.run(port=8080, debug=True)
print "Args List : %s\n" % (sys.argv) status_fl =0 # ------- Store Machines from pm_file -------- # print "Fetching available Physical Machines..." status_fl = GetPhysicalMachines(sys.argv[1]) if status_fl == 0: print "Physical Machines stored successfully!\n" else: print "Failed to store Physical Machines.\n" # ------- Load Images from image_file -------- # print "Loading OS Images from Image File..." status_fl = LoadImagesFromFile(sys.argv[2]) if status_fl==0 : print "Images loaded successfully!\n" else: print "Failed to load Images.\n" # ------- Creating temp folder -------- # if not os.path.isdir("temp"): os.mkdir("temp") print "Creating 'temp' folder for server manipulations...\n" # ------- Start the Flask Server -------- # if status_fl == 0: app.run(host='0.0.0.0', debug=True) else: print "[ERROR] : Failed to load server!"
#NOT being run in main thread so signals needs to be disabled rospy.init_node('rostopic', anonymous=True, disable_rosout=True, disable_rostime=True, disable_signals=True) pub = rospy.Publisher(topic_name, msg_class, latch=True, queue_size=100) argv_publish(pub, msg_class, [yaml.load(JSONEncoder().encode(msg))], None, True, False) return {'msg': 'PLEASE WAIT FOR ROBOT TO MOVE', 'status': 'PUBLISHED', 'body': request.data}, status.HTTP_200_OK @app.route('/poll', methods=['POST']) def poll(): topic_name = request.data.get('topic', None) if topic_name is None: return status.HTTP_400_BAD_REQUEST else: print echo_publisher(topic_name, 1) return yaml.load(str(echo_publisher(topic_name, 1))) @app.route('/type/{<string:name>}/', methods=['GET']) def get_type(name): """ :param name: :return: """ print name return 'ok' if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
from flask.ext.api import FlaskAPI import os import boto import boto.s3.connection access_key = os.environ['AWS_ACCESS_KEY'] secret_key = os.environ['AWS_SECRET_KEY'] conn = boto.connect_s3( aws_access_key_id = access_key, aws_secret_access_key = secret_key, #is_secure=False, # uncomment if you are not using ssl calling_format = boto.s3.connection.OrdinaryCallingFormat(), ) app = FlaskAPI(__name__) @app.route('/get_job/<id>') def example(): return {'hello': 'world'} app.run(host=os.environ['HOST'], post=int(os.environ['PORT']), debug=True)
s += str(num) return int(s) @app.route("/calc", methods=['GET']) def calculate_eqs(): l = int(request.args.get('l')) r = int(request.args.get('r')) total = int(request.args.get('t')) lrange = range(l, r + 1) equations = [' '.join(e) for e in find_matches(lrange, total) if solve(e)] return jsonify(equations) @app.route('/') def root(): print 'hit index' return send_from_directory('app', 'index.html') @app.route('/<path:path>') def send_static(path): return send_from_directory('app', path) if __name__ == "__main__": app.run(host="0.0.0.0")
return error_details, status.HTTP_400_BAD_REQUEST @app.errorhandler(GraphQLError) def handle_invalid_graph_error(graphql_error): error_message = format_error(graphql_error) logger.error(error_message) return {'error': error_message}, status.HTTP_400_BAD_REQUEST @app.route('/health-check') @app.route('/ping') def health_check(): """ Health check """ return {'reply': 'pong'} @app.route("/spec") def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "Demo of graphql API endpoint" return swag if __name__ == '__main__': app.debug = app.config['DEBUG'] app.run(host='0.0.0.0', port=5000)
.filter(and_(Directory.owner == username, Directory.path != "/") )\ .all() if files is not None: files = [f.to_dict() for f in files] dirs = [d.path for d in dirs] return {'files': files, 'dirs': dirs} @api.route("/api/everything/<string:username>") def list_history(username): txns = g.db.query(Transaction)\ .filter_by(user=username).all() old_paths = [tx.pathname for tx in txns] files = g.db.query(File).filter_by(owner=username).all() file_paths = [file.to_dict()['file_path'] for file in files] dirs = g.db.query(Directory)\ .filter(and_(Directory.owner == username, Directory.path != "/") )\ .all() dir_paths = [dir.path for dir in dirs] everything = set(file_paths + dir_paths + old_paths) return {'everything': list(everything) } if __name__ == '__main__': api.run(host='0.0.0.0', port=5000, debug=True)
@app.route("/", methods=['GET']) def home(): return {"Welcome": "Welcome to the Caribewave API!"} @app.route("/places", methods=['GET']) def places(): if os.path.exists(settings.PLACES_FILE): f = open(settings.PLACES_FILE) return json.loads(f.read()) return [] @app.route("/events/dates", methods=['GET']) def events_dates(): return list_events_dates() @app.route("/app/register_token", methods=['POST']) def register_token(): sns.create_endpoint(request.data["token"]) return {"status": "ok"} if __name__ == "__main__": app.run( port=8080, debug=settings.DEBUG)
@app.route("/v1/integration", methods=['GET','OPTIONS','POST']) @crossdomain(origin='*') def _add_integration(): #TODO - three fields, company_name, website, domain # - really only need 1 token = request.args["token"] user = request.args["user"] user_company = request.args["user_company"] print request.args print token, user, user_company, request.args["source"] if "google" in request.args["source"]: q.enqueue(Integrations()._google_contact_import, token, user, user_company) elif "salesforce" in request.args["source"]: print "SALESFORCE" instance_url = request.args["instance_url"] q.enqueue(Integrations()._salesforce_import, token, instance_url, user, user_company) return {"started":True} if __name__ == "__main__": app.run(debug=True, port=4000) ''' https://github.com/rsimba/heroku-xvfb-buildpack.git https://github.com/tstachl/heroku-buildpack-selenium.git https://github.com/srbartlett/heroku-buildpack-phantomjs-2.0.git https://github.com/leesei/heroku-buildpack-casperjs.git ''' # lol
"""The guest counts""" data = flask.request.get_json() customer_data = find_customer(data) amount = get_amount(customer_data) remove_customer(customer) return response({'amount': amount}) @app.route('/add_item', methods=['POST']) def add_item(): """Add an additional service""" data = flask.request.get_json() customer = find_customer(data) add_item(item, customer) return response({'amount': amount, 'item':item}) @app.route('/get_customer', methods=['POST']) def get_customer(): return customers app.run()
#!/usr/bin/python # coding=utf-8 from flask.ext.api import FlaskAPI from conf.config import LocalConfig from modules.authentication import authentication, auth from modules.authors import authors from modules import mongo application = FlaskAPI(__name__) application.config.from_object(LocalConfig) application.register_blueprint(authentication, url_prefix='/authentication') application.register_blueprint(authors, url_prefix='/authors') mongo.init_app(application) @application.route('/') @auth.login_required def index_testing(): return {'status': 'OK'} if __name__ == "__main__": application.run( host=application.config['HOST'], debug=application.config['DEBUG'], port=application.config['PORT'], )
@app.route("/api/prices", methods=['DELETE']) def pricesdelete(): id = request.args.get('id') DB.deleteprices(id) return '' @app.route("/api/sales") def sales(): id = request.args.get('id') return DB.getsales(id) @app.route("/api/sales", methods=['DELETE']) def salesdelete(): id = request.args.get('id') DB.deletesales(id) return '' @app.route("/api/reports/prices") def pricechanges(): id = request.args.get('id') return DB.getPriceChanges(id) if __name__ == '__main__': app.run(debug=True, port=3001, threaded=True, host='0.0.0.0')
@app.route("/api/end/<key>") def end(key): if key == current_app.admin_key: Contribution.pay_contributions() current_app.game_active = False return { 'paid': True, 'status': False }, status.HTTP_200_OK else: return { 'paid': False, 'status': current_app.game_active }, status.HTTP_400_BAD_REQUEST @app.route("/api/start/<key>") def start(key): if key == current_app.admin_key: current_app.game_active = True return { 'status': True }, status.HTTP_200_OK else: return { 'status': current_app.game_active }, status.HTTP_400_BAD_REQUEST @app.route("/api/status/") def game_status(): if current_app.game_active: return { 'status': current_app.game_active }, status.HTTP_200_OK else: return { 'status': current_app.game_active }, status.HTTP_503_SERVICE_UNAVAILABLE if __name__ == "__main__": app.run(debug=True, port=5001)
persistencia = PersistenciaTweets() # Manda insertar los tweets en la base de datos persistencia.insert_tweets(tweet.values() for tweet in tweets) # devuelve un JSON con los tweets y el código de la solicitud tweets_bd = persistencia.get_tweets_by_hashtag( buscador.to_hashtag(titulo)) if len(tweets_bd) > 0: return tweets_bd, status.HTTP_200_OK else: return {'message': 'No tweets found'}, status.HTTP_404_NOT_FOUND else: # Mensaje de error error_response = {'message': 'Parámetros incompletos'} # Devuelve el mensaje de error y el código de la solicitud return error_response, status.HTTP_400_BAD_REQUEST ''' -------------------------------------------------------------------------------- Ejecución del microservicio -------------------------------------------------------------------------------- ''' if __name__ == '__main__': print '--------------------------------------------------------------------' print 'Servicio sv_gestor_tweets' print '--------------------------------------------------------------------' port = int(os.environ.get('PORT', 8084)) app.debug = True app.run(host='0.0.0.0', port=port)
DBSession = sessionmaker(bind=engine) session = DBSession() app = FlaskAPI(__name__) CORS(app) app.debug = True @app.route('/get_contactos', methods = ['GET']) def get_contactos(): myContacto = session.query(Contactos).all() myContacto = [i.serialize for i in myContacto] return json.dumps(myContacto) @app.route('/post_contacto/<string:nombre>/<string:telefono>/<string:movil>/<string:calle>/<string:colonia>/<string:cp>', methods = ['POST']) def post_contacto(nombre, telefono, movil, calle, colonia, cp): contacto = Contactos(nombre, telefono, movil, calle, colonia, cp) session.add(contacto) session.commit() return "Contacto Agregado" @app.route('/delete_contacto/<int:id>', methods = ['DELETE']) def delete_contacto(id): contacto = session.query(Contactos).filter_by(id = id).one() session.delete(contacto) session.commit() return "Contacto eliminado" if __name__ == "__main__": app.run(host='127.0.0.1', port=5000)
@app.route('/clap') @basic_auth.required def clap(): session = Performance.Query.all().limit(1) if len(session) is 0: session = Performance(name='Keynote') session.save() else: session = session.get() try: # Accepts an incoming missed call log # Logs the entry to Parse user = Clap.load(request.args) user.session = session user.save() return user.to_dict() except ResourceRequestBadRequest as e1: print(e1) # TODO: do something more useful here pass except Exception as e: # TODO: do something more useful here print(e) pass # Ensure the drop off happens return dict(status=True) if __name__ == "__main__": app.run(port=port)
@app.route('/<path:meipath>/info.json', methods=['GET']) def information(meipath): try: mei_as_text = get_external_mei(meipath) except CannotAccessRemoteMEIException as ex: return {"message": ex.message}, status.HTTP_400_BAD_REQUEST except UnknownMEIReadException as ex: return {"message": ex.message}, status.HTTP_500_INTERNAL_SERVER_ERROR try: parsed_mei = meiinfo.read_MEI(mei_as_text).getMeiDocument() except CannotReadMEIException as ex: # return a 500 server error with the exception message return {"message": ex.message}, status.HTTP_500_INTERNAL_SERVER_ERROR # it's possible that this will raise some exceptions too, so break it out. try: mus_doc_info = meiinfo.MusDocInfo(parsed_mei).get() except BadApiRequest as ex: return {"message": ex.message}, status.HTTP_500_INTERNAL_SERVER_ERROR return mus_doc_info if __name__ == "__main__": host = os.environ.get('OMAS_HOST', '127.0.0.1') port = int(os.environ.get('OMAS_PORT', 5000)) app.run(host=host, port=port, debug=True)
Retrieve, update or delete note instances. """ if request.method == 'POST': stage_round(key,request.data.post('round', '')) return staged_games_text(key) # request.method == 'GET' if key not in DB['Sessions'].keys(): raise exceptions.NotFound() return staged_games_text(key) @app.route("/<int:key>/stage_round/<int:r>", methods=[ 'GET']) def notes_detail(key,r): """ Retrieve, update or delete note instances. """ # request.method == 'GET' if request.method == 'POST': stage_round(key,request.data.post('round', '')) return stage_update_status_req(key) if key not in DB['Sessions'].keys(): raise exceptions.NotFound() if stage_update_status(): return stage return stage_update_status_req(key) if __name__ == "__main__": app.run(debug=False)
value = data.get('value') measure_time_dt = datetime.fromtimestamp(data.get('measure_time'), local_timezone) measure_time = measure_time_dt.strftime('%H:%M:%S') datapoints.append({'title': measure_time, 'value': value}) num_datapoints = len(datapoints) if num_datapoints == 200: log.info( '%s datapoints found. This is the max permissable and may be truncated' % num_datapoints) else: log.info('%s datapoints found' % num_datapoints) graph_result['graph']['datasequences'] = [{ 'datapoints': datapoints, 'title': source }] except KeyError: log.info('No datapoints found in the metric query') graph_result['graph']['error'] = {} graph_result['graph']['error']['message'] = 'No datapoints found' finally: return graph_result if __name__ == '__main__': app.run(debug=os.environ['DEBUG'])
) if request.method == 'DELETE': subprocess.check_call(['chrome-cli', 'close', '-t', str(id)]) return {'message': 'Tab closed successfully'} if request.method == 'PUT': url = request.data.get('url') args = ['chrome-cli', 'open', str(url), '-t', str(id)] subprocess.check_call(args) return redirect(url_for('tab_detail', id=tab['id'])) return tab @app.route('/tabs/current', methods=['GET', 'PUT', 'DELETE']) def tab_current(): if request.method == 'DELETE': subprocess.check_call(['chrome-cli', 'close', '-t', str(id)]) return {'message': 'Tab closed successfully'} current_tab = _tab_info_str_to_dict( subprocess.check_output(['chrome-cli', 'info']), request ) return redirect(url_for('tab_detail', id=current_tab['id'])) if __name__ == '__main__': args = parser.parse_args() app.run(host=args.host, port=args.port, debug=args.debug)
Alex.learn('iu.aiml') Alex.learn('startup.aiml') Alex.learn('mp3.aiml') Alex.learn('politics.aiml') Alex.learn('knowledge.aiml') Alex.learn('mp4.aiml') Alex.learn('stories.aiml') Alex.learn('literature.aiml') Alex.learn('mp5.aiml') Alex.learn('primitive-math.aiml') Alex.learn('that.aiml') Alex.learn('reduction3.safe.aiml') Alex.learn('reduction4.safe.aiml') Alex.learn('reductions-update.aiml') Alex.learn('drugs.aiml') Alex.learn('biography.aiml') Alex.learn('bot.aiml') Alex.learn('bot_profile.aiml') Alex.learn('food.aiml') Alex.learn('client.aiml') Alex.learn('geography.aiml') Alex.learn('gossip.aiml') @app.route('/<question>') def ask(question): response = Alex.respond(question) return response if __name__=='__main__': app.run(debug=True, port=8000)
error_message = format_error(graphql_error) logger.error(error_message) return {'error': error_message}, status.HTTP_400_BAD_REQUEST @app.route('/suco') def coco(): return {'data': {'message': 'coco', 'status': '200'}} @app.route('/health-check') @app.route('/ping') def health_check(): """ Health check """ return {'reply': 'pong'} @app.route("/spec") def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "Demo of graphql API endpoint" return swag if __name__ == '__main__': app.debug = app.config['DEBUG'] app.run(host='0.0.0.0', port=5000)
except: import traceback return traceback.format_exc() finally: db.session.remove() @requires_auth @app.route('/recommendation/<string:id>/<datetime:date>',methods = ['GET']) def get_recommendation_on_date(id,date): """get recommend stocks on specified date""" try: s = db.session.query(scheme).filter_by(id = id).first() if s == None: return [] return [ r.to_dict() for r in s.recommend_stocks if r.recommendation_operation_date == date ] except: import traceback return traceback.format_exc() finally: db.session.remove() if __name__ == '__main__': #import os #HOST = os.environ.get('SERVER_HOST', '0.0.0.0') #try: # PORT = int(os.environ.get('SERVER_PORT', '5555')) #except ValueError: # PORT = 5555 app.run('0.0.0.0', 5555)
return { 'msg': 'PLEASE WAIT FOR ROBOT TO MOVE', 'status': 'PUBLISHED', 'body': request.data }, status.HTTP_200_OK @app.route('/poll', methods=['POST']) def poll(): topic_name = request.data.get('topic', None) if topic_name is None: return status.HTTP_400_BAD_REQUEST else: print echo_publisher(topic_name, 1) return yaml.load(str(echo_publisher(topic_name, 1))) @app.route('/type/{<string:name>}/', methods=['GET']) def get_type(name): """ :param name: :return: """ print name return 'ok' if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
@app.route('/predict', methods=['POST']) @token_auth def predict(): from engines import content_engine item = request.data.get('item') num_predictions = request.data.get('num', 10) if not item: return [] res = content_engine.predict(str(item), num_predictions) #print res return res @app.route('/train') @token_auth def train(): from engines import content_engine print "data:" print request.args print "end." data_url = request.data.get('data-url', None) print "a" content_engine.train(data_url) return {"message": "Success!", "success": 1} if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0')
@app.route("/api/prices", methods=["DELETE"]) def pricesdelete(): id = request.args.get("id") DB.deleteprices(id) return "" @app.route("/api/sales") def sales(): id = request.args.get("id") return DB.getsales(id) @app.route("/api/sales", methods=["DELETE"]) def salesdelete(): id = request.args.get("id") DB.deletesales(id) return "" @app.route("/api/reports/prices") def pricechanges(): id = request.args.get("id") return DB.getPriceChanges(id) if __name__ == "__main__": app.run(debug=True, port=3001, threaded=True, host="0.0.0.0")
dia) + " " + str(hora) + ":" + str(minutos) + ":00',\ INTERVAL " + margen + " MINUTE) AND pueblo_origen=" + origen + " AND destino=" + destino + " AND EsDeVuelta=" + vuelta #print (consultaInsertarViaje) conexionCreaViaje = conexion.conectar() cursorCreaViaje = conexionCreaViaje.cursor() cursorCreaViaje.execute(consultaInsertarViaje) conexionCreaViaje.close() res = dict() for id_viaje, salida, llegada, detalles, id_usuario, plazas, precio, destino, EsDeVuelta, pueblo_origen, telefono in cursorCreaViaje: #salida_fecha= datetime.datetime.strptime(str(salida),"%Y-%M-%D %H:%M:%S").datetime() salida_fecha = salida salida_dia = salida_fecha.day salida_hora = salida_fecha.hour salida_minuto = salida_fecha.minute res[id_viaje] = { "dia": salida_dia, "hora": salida_hora, "minutos": salida_minuto, "detalles": detalles, "id_usuario": id_usuario, "plazas": plazas, "precio": str(precio), "telefono": str(telefono), "EsDeVuelta": str(EsDeVuelta) } return res app.run(debug=True, host='0.0.0.0')
"zip": zip, "phone_home": phone, "geo": { "lat": str(lat), "lng": str(lng) }, "escalation": escalation } customers.append(customer) # Cleanup DB stuff q_cursor.close() cnx.close() # Process response and return response = { "meta": { "num_records": len(customers), "route_id": route_id }, "data": { "customers": customers } } return response if __name__ == "__main__": app.run('10.51.236.201', debug=True)
return {"message": "Success!", "success": 1} # note that backup.csv has fields: [id,title,author,date,content]. @app.route("/update") @token_auth def update(): title = request.data.get("title") author = request.data.get("author") date = request.data.get("date") url = request.data.get("url") content = request.data.get("content") if content and len(content) > 100: with open("backup.csv") as source: reader = csv.DictReader(source.read().splitlines()) # return "number of row: " + str(len(list(reader))) # return the number of rows inside backup.csv, used as next index. rowid = str(len(list(reader))) newrow = map(toUTF, [rowid, title, author, date, url, content]) with open("backup.csv", "a") as target: writer = csv.writer(target) writer.writerow(newrow) # return newrow # instead of returning that new post(look redundant), show a successful meg just be fine! return "Your post: <" + title + "> has been succesfully uploaded to databased!!!" else: return "Just a reminder that it's successfully updated, while it won't modify the database for now." if __name__ == "__main__": app.debug = True app.run()
for js_file in example_item["js"]: js_files.append(url_for("static", filename=js_file)) print(js_files) return render_template(example_item["template"], js_files=js_files) else: # Invalid ID abort(404) @app.route("/") @set_renderers(HTMLRenderer) def hello(): """ Missing docstring. """ example_links = [] for example_id in list(example_types.keys()): example_links.append({ "name": example_types[example_id]["name"], "url": "/example/{0}/".format(example_id) }) return render_template('example-list.html', js_files=[], example_links=example_links) if __name__ == "__main__": app.debug = True app.run(host=sys.argv[1], port=int(sys.argv[2])) #app.run(host='127.0.0.1', port=5000)
from flask import json, Response from flask.ext.api import FlaskAPI import requests app = FlaskAPI(__name__) @app.route('/feeds') def feeds_list(): feeds = [] page = requests.get('http://www.cresol.com.br/site/rss/news2.php?l=20').text soup = BeautifulSoup(page, "html.parser") for item in soup.find_all('item'): feed = {} feed['id'] = item.id.string feed['title'] = item.title.string feed['content'] = str(item.content).replace('<content>', '').replace('</content>', '') feed['description'] = item.description.string feed['image'] = item.image.string feed['link'] = item.link.string feed['pubDate'] = item.pubdate.string if item.video is not None: feed['video'] = item.video.string feeds.append(feed) return Response(json.dumps(feeds), mimetype='application/json') if __name__ == '__main__': #app.run(debug=True) app.run(host='0.0.0.0')
try: con = sqlite3.connect("database.db") cur = con.cursor() cur.execute("SELECT show FROM show_message") if cur.fetchone()[0] == 'yes': cur.execute("SELECT seconds, name, message " "FROM show_message LEFT JOIN users ON show_message.mac = users.mac") remaining_time, user, message = cur.fetchone() remaining_time = int(remaining_time) - 1 if remaining_time == 0: cur.execute("UPDATE show_message SET seconds=?, show=? WHERE id = 0", (remaining_time, 'no')) else: cur.execute("UPDATE show_message SET seconds=?", (remaining_time,)) con.commit() return render_template('message.html', user=user) else: return render_template('message.html') except: con.rollback() return jsonify({ 'performed': False, 'error': 'error occurred during inserting into database' }), status.HTTP_404_NOT_FOUND finally: con.close() if __name__ == "__main__": app.run(host='0.0.0.0', debug=False)
idx = max(notes.keys()) + 1 notes[idx] = note return note_repr(idx), status.HTTP_201_CREATED # request.method == 'GET' return [note_repr(idx) for idx in sorted(notes.keys())] @app.route("/<int:key>/", methods=['GET', 'PUT', 'DELETE']) def notes_detail(key): """ Retrieve, update or delete note instances. """ if request.method == 'PUT': note = str(request.data.get('text', '')) notes[key] = note return note_repr(key) elif request.method == 'DELETE': notes.pop(key, None) return '', status.HTTP_204_NO_CONTENT # request.method == 'GET' if key not in notes: raise exceptions.NotFound() return note_repr(key) if __name__ == "__main__": app.run(debug=True)
from flask.ext.api import FlaskAPI app = FlaskAPI(__name__) @app.route('/') def hello_world(): return {'hello': 'world'} if __name__ == "__main__": app.run(debug=True, port=3000, host='0.0.0.0')
if request.method == 'POST': note = str(request.data.get('text', '')) idx = max(notes.keys()) + 1 notes[idx] = note return note_repr(idx), status.HTTP_201_CREATED # request.method == 'GET' return [note_repr(idx) for idx in sorted(notes.keys())] @app.route("/<int:key>/", methods=['GET', 'PUT', 'DELETE']) def notes_detail(key): """ Retrieve, update or delete note instances. """ if request.method == 'PUT': note = str(request.data.get('text', '')) notes[key] = note return note_repr(key) elif request.method == 'DELETE': notes.pop(key, None) return '', status.HTTP_204_NO_CONTENT # request.method == 'GET' if key not in notes: raise exceptions.NotFound() return note_repr(key) if __name__ == "__main__": app.run(debug=True)
# Demo application that notify a message coming from REST API to a message bus (rabbitmq) from flask.ext.api import FlaskAPI, status from flask import request from postman import Postman app = FlaskAPI(__name__) # Msg bus configuration postman = Postman('app/config.ini') @app.route('/notify', methods=['POST']) def notify(): msg = request.form['msg'] postman.send_message(msg) return '', status.HTTP_201_CREATED if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)