本文整理汇总了Python中flask.ext.api.FlaskAPI.run方法的典型用法代码示例。如果您正苦于以下问题:Python FlaskAPI.run方法的具体用法?Python FlaskAPI.run怎么用?Python FlaskAPI.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.ext.api.FlaskAPI
的用法示例。
在下文中一共展示了FlaskAPI.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: str
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
)
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)
示例2: send_file
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
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')
示例3: home
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
@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)
示例4: login
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
@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='John Doe'))
@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()
示例5: FlaskAPI
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
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)
示例6: query
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
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)
示例7: str
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
"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)
示例8: FlaskAPI
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
#!/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)
示例9: end
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
@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)
示例10: get_recommendation_on_date
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
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)
示例11: argv_publish
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
#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)
示例12: handle_invalid_graph_error
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
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)
示例13: list_history
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
.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)
示例14: password
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
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)
示例15: print
# 需要导入模块: from flask.ext.api import FlaskAPI [as 别名]
# 或者: from flask.ext.api.FlaskAPI import run [as 别名]
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)