def index(): text = request.args.get('text') json_type = 'application/json' json_accepted = json_type in request.headers.get('Accept', '') if text: words = text.split() reversed_words = [word[::-1] for word in words] if json_accepted: res = response(json.dumps({'text': reversed_words}), 200) else: res = response(' '.join(reversed_words), 200) else: res = response('text not found', 501) res.headers['Content-Type'] = json_type if json_accepted else 'text/plain' return res
def checkout_customer(): """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})
def autocomplete(): client = pymongo.MongoClient() db = client.shortz_vod data = [] stages = [] q: str = request.args.get('term') if not q: return abort(404) matchField: dict = {} matchField["$text"] = {"$search": q} stages.append({"$match": matchField}) stages.append({"$sort": {"score": {"$meta": "textScore"}}}) stages.append({"$project": { "_id": 0, "create_at": 0, }}) stages.append({"$limit": 20}) d = db.autocomplete.aggregate(stages) data = [i['keyword'] for i in d] r = response(json.dumps(data)) r.headers["content-type"] = "application/json" return r, 200
def require_authorized_user(): username, password = env.get('COMMAND_LINE_BLOG_USER', None), env.get('COMMAND_LINE_BLOG_PWD', None) auth = request.authorization if not auth or (auth.username != username or auth.password != password): return response('Authentication required.', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
def _auth_decorator(*args, **kwargs): auth = request.authorization if not auth: return response("Could not authenticate you", 401, {"WWW-Authenticate":'Basic realm="Login Required"'}) else: if auth.username and auth.password: try: author = db_session.query(Author).filter_by(username=auth.username).first() except Exception: app.logger.debug(format_exc()) return response("Could not authenticate you", 401, {"WWW-Authenticate":'Basic realm="Login Required"'}) if not author or not check_password_hash(author.password, auth.password): return response("Could not authenticate you", 401, {"WWW-Authenticate":'Basic realm="Login Required"'}) else: return response("Could not authenticate you", 401, {"WWW-Authenticate":'Basic realm="Login Required"'}) session["user_name"] = author.username session["user_id"] = author.id return f(*args, **kwargs)
def put(id): try: glass = Glass.objects.get(id=id) except mongoengine.DoesNotExist: return flask.response('Not found', 404) data = flask.request.get_json() if 'name' in data: glass.name = data['name'] glass.save() return JSONResponse(glass.to_json())
def login(): _name = req.form['username'] _password = req.form['password'] _data = {"email": _name, "password": _password} # Validate the inpute values if _name and _password: if loginControl.signIn(_data): # _html = render('admin/index.html') # return json.dumps({'data' : _html}) # return json.dumps({'html' : '<span class="bg-success">Welcome back' + _name + '!</span>'}) # flash('You were successfully logged in') return response( "{'html' : '<span class=\"bg-success\">Welcome back' + _name + '!</span>'}", status=200) # Without ajax # return redirect(url_for('admin', next='/admin')) else: return response( "{'html' : '<span>Invalid email or password!</span>'}", status=409) else: return response("{'html' : '<span>Enter the required fields!</span>'}", status=400)
def put(id): """Updates a brewery by id""" try: brewery = Brewery.objects.get(id=id) except mongoengine.DoesNotExist: return flask.response('Not found', 404) data = flask.request.get_json() props = ['name', 'city', 'state'] for item in props: if item in data: setattr(brewery, item, data[item]) brewery.save() return JSONResponse(brewery.to_json())
def create(slug=None): import hashlib client = pymongo.MongoClient() db = client.shortz_vod client = pymongo.MongoClient() db = client.shortz_vod max_file_size = 100 * 1024 * 1024 f = request.files['file'] result = {"status": False} if f.mimetype != "application/x-zip-compressed": result[ 'log'] = "Veuillez utiliser un fichier zip {} n'est pas un fichier valide".format( escape(f.filename)) else: name = secure_filename(f.filename) filename = 'ftp/{}-{}.zip'.format(g.user['_id'], secrets.token_urlsafe(20).lower()) f.save(filename) f.seek(0, 2) file_length = f.tell() if file_length > max_file_size: result[ 'log'] = "Taille limite pour l'upload est de {}Mo par fichier".format( (max_file_size // 1024) // 1024) else: try: mezzanine_treatment(filename) result['log'] = "votre chiane a été creeé avec succès" result['status'] = True except Exception as e: result["log"] = str(e) r = response(json.dumps(result)) r.headers["content-type"] = "application/json" return r, 200
def page_not_found(e): error = {'status': 'bad requests'} error = json.dumps(error) resp = response(error, status=400, mimetype='application/json') return resp
def make_response(data, code=1): """返回json数据""" return response(obj_to_json({'code': code, 'data': data}))
def get_movie(movie_id=None): client = pymongo.MongoClient() db = client.shortz_vod if movie_id is not None: data = db.movie.aggregate([ { "$match": { "code": movie_id, "state": "ready", } }, { "$lookup": { "from": "channel", #"localField":"channel_id", #"foreignField":"_id", "let": { "localField": "$channel_id" }, "pipeline": [{ "$match": { "$expr": { "$and": [ { "$eq": ["$_id", "$$localField"] }, ] } } }, { "$project": { "user_id": 0, "create_at": 0 } }], "as": "channel", } }, { "$addFields": { "channel": { "$arrayElemAt": ["$channel", 0] } } }, { "$lookup": { "from": "view", "let": { "localField": "$_id" }, "pipeline": [ { "$match": { "$expr": { "$and": [ { "$eq": ["$movie_id", "$$localField"] }, ] } } }, { "$count": "total" }, ], "as": "views" } }, { "$addFields": { "views": { "$arrayElemAt": ["$views", 0] } } }, { "$project": { "_id": 0, "channel_id": 0, "user_id": 0, "channel._id": 0, } }, { "$sort": { "_id": -1 } }, { "$limit": 1 }, ]) if data is None: return abort(404) for i in data: i['image'] = url_for('static', filename='img/channels/{}'.format(i['image'])) i['cover'] = url_for('static', filename='img/channels/{}'.format(i['cover'])) i['duration'] = "6:25" i['source'] = url_for("live", movie_id=i['code'], seg="index", ext="m3u8") i["create_at"] = i['create_at'].strftime("%d %b %Y") if "views" in i: i['views'] = int(i["views"]["total"]) else: i['views'] = 0 data = i break else: data = [] stages = [] q: str = request.args.get('q') matchField: dict = {"state": "ready"} if not q: return abort(404) matchField["$text"] = {"$search": q} stages.append({"$match": matchField}) if "$text" in matchField: stages.append({"$sort": {"score": {"$meta": "textScore"}}}) stages.append({ "$lookup": { "from": "channel", "let": { "localField": "$channel_id" }, "pipeline": [{ "$match": { "$expr": { "$and": [ { "$eq": ["$_id", "$$localField"] }, ] } } }, { "$project": { "user_id": 0, "create_at": 0 } }], "as": "channel", } }) stages.append( {"$addFields": { "channel": { "$arrayElemAt": ["$channel", 0] } }}) # les vues stages.append({ "$lookup": { "from": "view", "let": { "localField": "$_id" }, "pipeline": [ { "$match": { "$expr": { "$and": [ { "$eq": ["$movie_id", "$$localField"] }, ] } } }, { "$count": "total" }, ], "as": "views" } }) stages.append( {"$addFields": { "views": { "$arrayElemAt": ["$views", 0] } }}) stages.append({ "$project": { "_id": 0, "channel_id": 0, "user_id": 0, "channel._id": 0, } }) stages.append({"$limit": 5}) d = db.movie.aggregate(stages) for i in d: i['image'] = url_for('static', filename='img/channels/{}'.format(i['image'])) i['cover'] = url_for('static', filename='img/channels/{}'.format(i['cover'])) i['duration'] = "6:25" i['source'] = url_for("live", movie_id=i['code'], seg="index", ext="m3u8") i["create_at"] = i['create_at'].strftime("%d %b %Y") if "views" in i: i['views'] = int(i["views"]["total"]) else: i['views'] = 0 data.append(i) r = response(json.dumps(data)) r.headers["content-type"] = "application/json" return r, 200
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})
def get_movie_similar(movie_id): client = pymongo.MongoClient() db = client.shortz_vod mh = request.cookies.get("mh", None) if mh is None: mh = [] else: mh = mh.split(",") if movie_id not in mh: mh.append(movie_id) movie = db.movie.find_one({ "code": movie_id, "state": "ready", }) if movie is None: return abort(404) data = db.movie.aggregate([ { "$match": { "code": { "$nin": mh }, "state": "ready", "keywords": { "$elemMatch": { "$in": movie['keywords'] } } } }, { "$lookup": { "from": "channel", "let": { "localField": "$channel_id" }, "pipeline": [{ "$match": { "$expr": { "$and": [ { "$eq": ["$_id", "$$localField"] }, ] } } }, { "$project": { "user_id": 0, "create_at": 0 } }], "as": "channel", } }, { "$addFields": { "channel": { "$arrayElemAt": ["$channel", 0] } } }, { "$lookup": { "from": "view", "let": { "localField": "$_id" }, "pipeline": [ { "$match": { "$expr": { "$and": [ { "$eq": ["$movie_id", "$$localField"] }, ] } } }, { "$count": "total" }, ], "as": "views" } }, { "$addFields": { "views": { "$arrayElemAt": ["$views", 0] } } }, { "$project": { "_id": 0, "channel_id": 0, "user_id": 0, "channel._id": 0, } }, { "$sort": { "_id": -1 } }, { "$limit": 2 }, ]) similar_movies = [] for i in data: i['image'] = url_for('static', filename='img/channels/{}'.format(i['image'])) i['cover'] = url_for('static', filename='img/channels/{}'.format(i['cover'])) if i['hours']: i['duration'] = "{:02}:{:02}:{:02}".format(i["hours"], i["minutes"], i["seconds"]) else: i['duration'] = "{:02}:{:02}".format(i["minutes"], i["seconds"]) i['source'] = url_for("live", movie_id=i['code'], seg="index", ext="m3u8") i["create_at"] = i['create_at'].strftime("%d %b %Y") if "views" in i: i['views'] = int(i["views"]["total"]) else: i['views'] = 0 similar_movies.append(i) r = response(json.dumps(similar_movies)) r.headers["content-type"] = "application/json" r.set_cookie('mh', ",".join(mh), max_age=3600, expires=time.time() + 3600, httponly=True) return r, 200
def make_no_data_response(desc=None, code=1): """正常返回""" return response(obj_to_json({'code': code, 'desc': desc}))
def make_response_not_to_json(data): """返回raw数据""" return response(data)
def make_error_response(desc=None, code=-1): """返回错误""" return response(obj_to_json({'code': code, 'desc': desc}))
def page_not_found(e): error = {'status': 'bad password or username'} error = json.dumps(error) resp = response(error, status=401, mimetype='application/json') return resp
def page_not_found(e): error = {'status': 'forbidden to access'} error = json.dumps(error) resp = response(error, status=403, mimetype='application/json') return resp
def page_not_found(e): error = {'status': 'methods not allowed'} error = json.dumps(error) resp = response(error, status=405, mimetype='application/json') return resp
def page_not_found(e): error = {'status': 'page not found'} error = json.dumps(error) resp = response(error, status=404, mimetype='application/json') return resp