def login_in(): content = request.data try: data = json.loads(str(content, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) mobile = data.get('mobile') password = data.get('password') code = data.get('code') if not mobile or not password: return jsonify(Result().fail(code="param.null", msg="Invalid username/password")) if not code: captcha = RequestUtil.get_captcha(session) if code != captcha: return jsonify(Result().fail(code="error.captcha")) user = user_service.find_by_user(mobile, password) if user: session["user_id"] = str(user.id) session["mobile"] = str(user.mobile) user.update(login_time=datetime.datetime.now()) return jsonify(Result().success({"id": str(user.id)})) else: return jsonify(Result().fail(code="user.not.exists", msg="user not exists"))
def create(): user_id = session.get("user_id") content = request.data try: data = json.loads(str(content, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) pros = data.get('pros') areas = data.get('areas') name = data.get('name') mobile = data.get('mobile') address = data.get('address') save = OrdSave() for pro in pros: pid = pro.split("_")[0] num = pro.split("_")[1] product = product_service.find_by_id(pid) if not product: return jsonify(Result().fail(code="product.not.exist", msg="product not exist")) save.add_product({ "id": str(product.id), "num": num, "title": product.title }) save.areas = areas save.name = name save.mobile = mobile save.address = address save.user_id = user_id save.status = 1 id = ord_service.save(save) return jsonify(Result().success({"id": id}))
def save(): try: data = json.loads(str(request.data, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) area = data.get('area') year = data.get('year') unit = data.get('unit') print1 = data.get('print') num_start = int(data.get('num_start')) num_end = int(data.get('num_end')) if not area or not year or not unit or not num_start or not print1: return jsonify(Result().fail(code="param.null", msg="Invalid param")) if len(area) != 2 or len(year) != 4 or len(unit) != 2 or len(print1) != 2: return jsonify(Result().fail(code="param.length", msg="param length error")) if num_end - num_start > 1000: return jsonify(Result().fail(code="param.range", msg="end - start over 1000")) for num in range(int(num_start), int(num_end)): code = GiftCardCode() code.area = area code.year = year code.unit = unit code.print = print1 code.num = num if gift_card_service.find_by_code(code.code()) is None: gift_card_service.save(code) return jsonify(Result().success())
def plot_total_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) # Python function to plot active cases return result.plot_total(model.today)
def delete(aid): user_id = session.get(const.SESSION_USER_ID) ua = user_address_service.find_by_id(aid) if ua.user_id != user_id: return jsonify(Result().fail(code="error.not.yours")) if ua: user_address_service.delete(aid) return jsonify(Result().success())
def plot_active_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) # Python function to render output panel return result.plot_active(model.today)
def _construct_player(self, command): result = P.decode_player(command) if not result.success: return Result.get_negative() name, number_of_players = result.result return Result.get_positive(Player(self.player.get_connection, name, number_of_players))
def delete(uid): user_id = session.get(const.SESSION_USER_ID) if user_id == uid: return jsonify(Result().fail(code="error.delete.yourself")) u = user_service.find_by_id(uid) if not u: return jsonify(Result().fail(code="error.not.exists")) user_service.delete(uid) return jsonify(Result().success())
def update(): try: data = json.loads(str(request.data, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) code = str(data['code']) password = str(data['password']) id = gift_card_service.update_used(code, password) return jsonify(Result().success())
def _add_to_group(self): result = self._check_available_groups() if not result.success: return Result.get_negative() self._add_player_to_queue() result.result.add([self.player]) return Result.get_positive()
def save(): content = request.data try: data = json.loads(str(content, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) address = UserAddress() address.user_id = session.get("user_id") get_address_from_json(address, data) aid = user_address_service.save(address) return jsonify(Result().success({"id": aid}))
def delete(oid): user_id = RequestUtil.get_user_id(session) ord_db = ord_service.find_by_id(oid) if not ord_db: return jsonify(Result().fail(code="ord.not.exists")) if not ord_db['ord'].user_id: ord_service.delete(oid) return jsonify(Result().success()) if ord_db['ord'].user_id != user_id: return jsonify(Result().fail(code="ord.not.yours")) ord_service.delete(oid) return jsonify(Result().success())
def find_by_code(code): gift = gift_card_service.find_by_code(code) if not gift: current_app.logger.warn("can not find the gift code: %s" % code) return jsonify(Result().fail(code="gift_card.not.found")) pro = product_service.find_by_id(gift.product_id) if not pro: return jsonify(Result().fail(code="product.not.bind")) return jsonify(Result().success({ "gift_card": gift.to_dict(), "product": pro.to_dict() }))
def bind_product(): try: data = json.loads(str(request.data, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) product_id = str(data['product_id']) codes = data['codes'] p = product_service.find_by_id(product_id) if not p: return jsonify(Result().fail(code="product.not.found")) gift_card_service.update_bind_product(codes, product_id) return jsonify(Result().success())
def test_result_dict(self): self.assertDictEqual(Result().success(), {'code': 'success'}) self.assertDictEqual(Result().success("data"), { 'code': 'success', 'data': 'data' }) self.assertDictEqual(Result().fail(), {'code': 'fail'}) self.assertDictEqual(Result().fail(code="cod11e", msg="msg11"), { 'code': 'cod11e', 'msg': 'msg11' }) self.assertDictEqual(Result().fail(code="cod11e"), {'code': 'cod11e'})
def update(): content = request.data try: data = json.loads(str(content, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) id = str(data.get("id")) address = user_address_service.find_by_id(id) if not address: return jsonify(Result().fail("address.not.exists")) get_address_from_json(address, data) user_address_service.update(address) return jsonify(Result().success())
def api_upload(): upload = current_app.config.get("UPLOAD_IMAGE") now = datetime.date.today().isoformat() file_dir = os.path.join(upload, now.replace("-", "/")) if not os.path.exists(file_dir): os.makedirs(file_dir) f = request.files['file'] if f and allowed_file(f.filename): ext = f.filename.rsplit('.', 1)[1] if ext in ALLOWED_EXTENSIONS: new_filename = str(int(time.time())) + '_' + shortuuid.uuid()[:8] + "." + ext f.save(os.path.join(file_dir, new_filename)) return jsonify(Result().success("/file/img/" + new_filename)) return jsonify(Result().fail())
def decode_player(command: str): parts = command.split(ASSIGNMENT) if parts[0] == PLAYER: construction_arguments = parts[1].split(LIST_DELIMITER) if len(construction_arguments) == 2: try: return Result.get_positive((construction_arguments[0], int(construction_arguments[1]))) except ValueError as error: # WARNING Invalid argument return Result.get_negative(error) return Result.get_negative()
def update_head(): user_id = RequestUtil.get_user_id(session) try: data = json.loads(str(request.data, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) head = data.get('head_url') if not head: return jsonify(Result().fail(code="error.head.null")) u = user_service.find_by_id(user_id) if not u: current_app.logger.warn("can not find the user %s" % user_id) return jsonify(Result().fail(code="error.not.exists")) u.update(head_url=head, update_time=datetime.datetime.now()) return jsonify(Result().success())
def get_img(path): arr = path.split("_") time = arr[0] upload = current_app.config.get("UPLOAD_IMAGE") datepath = datetime.datetime.fromtimestamp(int(time)).date().isoformat() file_dir = os.path.join(upload, datepath.replace("-", "/"), path) if not os.path.exists(file_dir): ext = path.rsplit('.', 1)[1] orign_dir = os.path.join(upload, datepath.replace("-", "/"), "%s_%s.%s" % (arr[0], arr[1], ext)) print(orign_dir) if len(arr) > 2: wh_str = arr[2].split(".")[0] if not wh_str in ALLOWED_WIDTH_HEIGHT: return jsonify(Result().fail(code="wh.not.allow", msg="wh not allow")) wh = wh_str.split("x") if len(wh) > 1: # widthxheight.png print(orign_dir) print(file_dir) print(wh) clip_resize(orign_dir, file_dir, wh) else: # width.png thumbnail(orign_dir, file_dir, wh) with open(file_dir, 'rb') as f: return Response(f.read(), mimetype="image/jpeg")
def update(): try: data = json.loads(str(request.data, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) mobile = data.get('mobile') password = data.get('password') if not mobile: return jsonify(Result().fail(code="param.null", msg="Invalid username/password")) if not user_service.find_by_mobile(mobile): return jsonify(Result().fail(code="user.exists")) save = UserSave() save.mobile = mobile save.password = password uid = user_service.update(save) return jsonify(Result().success())
def get_super_csv(self) -> [Result]: results = [] for directory in os.listdir(self.path): csv_results = os.listdir(os.path.join(self.path, directory)) print(csv_results) for csv_result in csv_results: with open(os.path.join(self.path, directory, csv_result), encoding="utf8") as file: #with open(os.path.join(self.path, directory, csv_result)) as file: reader = csv.reader(file) for row in reader: if not row: continue if row[0] == 'title': continue results.append( Result(title=row[0], author=row[1], date=row[2], link=row[3], pdf_link=row[4], query=csv_result, search_engine=directory, cite_count=row[8], doi=row[9])) #results = count_similar_results(results) return results
def results(self): arguments = {'count': 10, 'full': True, 'revision': self.sha1} raw_results = self.client.execute_request(rest_resource='resultset', get_arguments=arguments) return [ Result.from_json(self.client, raw_result) for raw_result in raw_results ]
def update_password(): user_id = session.get(const.SESSION_USER_ID) content = request.data try: data = json.loads(str(content, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) password_old = data.get('password_old') password_new1 = data.get('password_new1') password_new2 = data.get('password_new2') if password_new1 != password_new2: return jsonify(Result().fail(code="new_password.not.equal")) u = user_service.find_by_id(user_id) if password_old != u.password: return jsonify(Result().fail(code="old_password.not.equal")) u.update(password=str(password_new1), update_time=datetime.datetime.now()) return jsonify(Result().success())
def _update_found_result(result: Result, found_result: Result): found_result.nr_found += 1 not_empty = (result.cite_count != ResultConstants.NO_CITE_COUNT and found_result.cite_count != ResultConstants.NO_CITE_COUNT) if not_empty: max_cite_count = max(_to_number(result.cite_count), _to_number(found_result.cite_count)) found_result.cite_count = str(max_cite_count)
def write(self, results: [], file_name: str): with open(self._path + file_name, 'w',encoding = "utf8", newline = '') as file: writer = csv.writer(file) keys = [key for key, value in vars(Result('', '', '', '', '')).items()] writer.writerow(keys) for result in results: values = [str(value).replace(';', '') for key, value in vars(result).items()] writer.writerow(values)
def save(): content = request.data try: data = json.loads(str(content, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) mobile = data.get('mobile') password = data.get('password') head_url = data.get('head_url') if not mobile or not password: return jsonify(Result().fail(code="param.null")) if user_service.find_by_user(mobile, password): return jsonify(Result().fail(code="user.exists", msg="user exists")) save = UserSave() save.mobile = mobile save.password = password save.head_url = head_url uid = user_service.save(save) return jsonify(Result().success({"id": uid}))
def save(): try: data = json.loads(str(request.data, encoding="utf-8")) except JSONDecodeError: return jsonify(Result().fail(code="error.json")) title = data.get('title') content = data.get('content') main_pic = data.get('main_pic') price = data.get('price') pics = data.get('pics') if not title or not content: return jsonify(Result().fail("param.none", "param.none")) save = ProductSave() save.title = title save.content = content save.price = price save.main_pic = main_pic save.pics = pics p = product_service.save(save) return jsonify(Result().success(p.code))
def detail(id): user_id = RequestUtil.get_user_id(session) detail = ord_service.find_by_id(id) if not detail or not detail.get("ord"): return jsonify(Result().fail(code="ord.not.exist")) if not detail.get("ord").user_id or user_id != detail.get("ord").user_id: return jsonify(Result().fail(code="ord.not.yours", msg="ord is not yours")) ps = list(map(lambda item: item.to_dict(), list(detail.get("products")))) return jsonify(Result().success({ "ord": detail.get("ord").to_dict(), "products": ps, "area": None if not detail.get("area") else detail.get("area").to_dict(), "gift_card": None if not detail.get("gift_card") else detail.get("gift_card").to_dict() }))
def reg(): content = request.data data = json.loads(str(content, encoding="utf-8")) mobile = data.get('mobile') password = data.get('password') password2 = data.get('password2') if not mobile or not password: return jsonify(Result().fail(code="param.null", msg="Invalid username/password")) if password != password2: return jsonify(Result().fail(code="password.not.equal", msg="password not equal")) if user_service.find_by_mobile(mobile): return jsonify(Result().fail(code="user.exists", msg="user exists")) else: save = UserSave() save.mobile = mobile save.password = password user_id = user_service.save(save) session["user_id"] = str(user_id) session["mobile"] = str(mobile) return jsonify(Result().success({"id": user_id}))
def search(self, q): """ Prepare elements for request and play it """ self.param = urlencode(self.param.myParam.get()) self.recherche = urlparse(self.recherche.my_recherche.get()) url = "%s%s%s" % ( self.recherche[1], self.recherche[2], self.recherche[3] ) ok, response, timer = self._requester() if not ok: self.error = Error() self.error.add_param( GT_('Erreur'), GT_('Url injoignable : %s\n%s') % (url, response) ) else: self.result = Result() self.result.unset() # Request information (url, execution time) self.result.add_param( GT_('http://%s en %d.%06d secondes') % ( url, timer.seconds, timer.microseconds ), '%s : %s' % (response.status, response.reason) ) # Request information (url, execution time) self.result.add_param( GT_('Entetes'), response.getheaders() ) version = 1.0 if response.version == 11: version = 1.1 self.result.add_param( GT_('Version du protocole'), GT_('HTTP/%s' % version) ) q.task_done()
class Action: """ Class Recherche Classe de controle de la vue "Recherche" """ def __init__(self): """ Constructeur du controleur de la vue "Recherche" A à sa charge la gestion des événements sur la vue "vue.Recherche" """ self.param = Parametre() self.recherche = Recherche() self.header = Header() def search(self, q): """ Prepare elements for request and play it """ self.param = urlencode(self.param.myParam.get()) self.recherche = urlparse(self.recherche.my_recherche.get()) url = "%s%s%s" % ( self.recherche[1], self.recherche[2], self.recherche[3] ) ok, response, timer = self._requester() if not ok: self.error = Error() self.error.add_param( GT_('Erreur'), GT_('Url injoignable : %s\n%s') % (url, response) ) else: self.result = Result() self.result.unset() # Request information (url, execution time) self.result.add_param( GT_('http://%s en %d.%06d secondes') % ( url, timer.seconds, timer.microseconds ), '%s : %s' % (response.status, response.reason) ) # Request information (url, execution time) self.result.add_param( GT_('Entetes'), response.getheaders() ) version = 1.0 if response.version == 11: version = 1.1 self.result.add_param( GT_('Version du protocole'), GT_('HTTP/%s' % version) ) q.task_done() def _requester(self): """ Execute request and return result """ try: methode = 'POST' if not self.param: methode = 'GET' debut = datetime.now() connection = httplib.HTTPConnection(self.recherche[1]) connection.request( methode, '%s/%s' % (self.recherche[2], self.recherche[3]), self.param, self.header.my_header.get() ) response = connection.getresponse() connection.close() timer = datetime.now() - debut return True, response, timer except socket.gaierror: return False, GT_("Socket erreur"), None except http.client.InvalidURL: return False, GT_("Url non valide"), None
def results(self): arguments = {'count': 10, 'full': True, 'revision': self.sha1} raw_results = self.client.execute_request(rest_resource='resultset', get_arguments=arguments) return [Result.from_json(self.client, raw_result) for raw_result in raw_results]