def inner(*args, **kwargs): if 'api_key' in request.form and 'api_secret' in request.form: post_key = request.form.get('api_key') post_secret = request.form.get('api_secret') # 查找缓存 cache_secret = alive_key.get(post_key) # 命中 if cache_secret is not None: if cache_secret == post_secret: return func(*args, **kwargs) else: raise ApiException('token error', "api_secret didn't match your api_key", 400) else: # 查找key是否存在数据库中,并检查合法性 key = Key.query.filter_by(api_key=post_key).first() if key is not None: if key.api_secret == post_secret: # 重新缓存当前key add_hotkey(key.api_key, key.api_secret) return func(*args, **kwargs) else: # 认证失败 raise ApiException( 'token error', "api_secret didn't match your api_key", 400) else: # 非法访问 raise ApiException( 'access error', "Could not find the key:{api_key}".format( api_key=post_key), 400) else: # 参数出错 raise ApiException('args error', "required api_key and api_secret", 400)
def dectect(): try: if 'image' in request.files: post_data = request.files.get('image').read() jpg_data = dn_handle.data_to_image(post_data) res = dn_handle.detect2(net, meta, jpg_data) return jsonify(res) else: raise ApiException('function dectect call error', 'please POST image file ,ex:image=@yourfiles', 400) except Exception as e: raise ApiException('Internal Server Error', 'please contact with server admin', 500)
def getValue(self, httpMethod, configuration, methodPath, pathParams, context, bodyObject, valueType): if (pathParams): for key, value in pathParams.iteritems(): methodPath = methodPath.replace("{" + key + "}", str(value)) url = configuration.base_url + methodPath username = configuration.username password = configuration.password api_key = configuration.api_key token = configuration.token if context: if isinstance(context, dict): params = urllib.urlencode(context) else: params = urllib.urlencode(context.to_dict()) url = url + ("?%s" % params) u = urlparse(url) if (u.scheme == "https"): connection = httplib.HTTPSConnection(u.netloc) else: connection = httplib.HTTPConnection(u.netloc) headers = {} if username: auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') headers["Authorization"] = "Basic %s" % auth if api_key: headers["Authorization"] = "ApiKey %s" % api_key if token: headers["Authorization"] = "IBSSO %s" % token body_content = None if bodyObject: body_content = self.serialize(bodyObject) headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" headers["User-Agent"] = "Python-Client-Library" connection.request(httpMethod, url, body_content, headers) response = connection.getresponse() statusCode = response.status response_content = response.read() if (statusCode < 200 or statusCode >= 300): contentType = response.getheader("Content-Type") if contentType and contentType.startswith("application/json"): raise self.deserialize(response_content, ApiException) raise ApiException(ApiRequestError(None, ApiRequestErrorDetails(response.reason + " - " + response_content))) contentType = response.getheader("Content-Type") if contentType and contentType.startswith("application/json") and not basestring == valueType: return valueType.from_JSON(response_content) return response_content
def currency_endpoint(): currency: str = request.form.get('value') if not currency: raise ApiException("Bad input") response = CurrencyResponse(currency) response.process() return response.get_html()
def _get_actual_info(self): output = requests.get( "http://api.nbp.pl/api/exchangerates/rates/a/%s/?format=json" % self.currency_code) if output.status_code != 200: raise ApiException( "Waluta %s nie istnieje.<br><br>Dostępne waluty:<br>%s" % (self.currency_code, self._get_available_currencies())) output = json.loads(output.content) self.currency_code = output.get("code") self.currency_name = output.get("currency") self.today_rate = CurrencyRate(str(output.get("rates")[0].get("mid")))
def check_required_params(self, *params): """ 校验必填的参数 :param params: 必填的参数名 :return: 如果所有必填参数都有设置,返回True,否则返回False,并且向客户端输出必填的参数列表 """ required = [] for param in params: v = self.get_argument(param, '') if v == '': required.append(param) if len(required) > 0: raise ApiException({'data': required, 'error': ErrNo.PARAMS_INVALID})
def cal_imagemean(): try: if 'image' in request.files: files = request.files data = files.get('image').read() from PIL import Image from StringIO import StringIO import numpy as np # 提取jpg图像的数据 # 流量大的情况,性能问题来自于并发处理的能力,此时可以使用redis等工具构建消息队列,来批量处理 # 流量不大的情况,如果使用缓存,对图像数据的序列化和反序列化的时间开销会明显影响性能 im_jpg = Image.open(StringIO(data)) img_data = np.asarray(im_jpg, dtype=np.uint8).transpose(2,0,1) # 返回图像平均值 return jsonify({'image':files.get('image').filename, 'meanvalue':img_data.mean()}) else: raise ApiException('function imagemean call error', 'please POST image file ,ex:image=@yourfiles', 400) except Exception as e: raise ApiException('Internal Server Error', 'please contact with server admin', 500)
def createkey(): new_app = request.form.get('appname') new_apptype = request.form.get('apptype') api_key = getmd5(current_user.name + str(new_app)) api_sercet = getmd5(current_user.password + str(time())) try: db.session.add( Key(current_user.name, new_app, new_apptype, api_key, api_sercet)) db.session.commit() return jsonify({ 'user': current_user.name, 'app_name': new_app, 'type': new_apptype, 'api_key': api_key, 'api_secret': api_sercet }) except Exception as e: raise ApiException( message='occur error when creating the api key, please retry')
def add(): num1 = request.args.get('a', type=int) num2 = request.args.get('b', type=int) if num1 is None or num2 is None: raise ApiException('Two integers are expected') return ApiResponse({'sum': num1 + num2})