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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 bind_product_range(): 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']) start_code = data['start_code'] end_code = data['end_code'] code = start_code[:-6] num_start = int(start_code[-6:]) num_end = int(end_code[-6:]) # 0120190101000011 p = product_service.find_by_id(product_id) if not p: return jsonify(Result().fail(code="product.not.found")) if num_end - num_start > 1000: return jsonify(Result().fail(code="param.range", msg="end - start over 1000")) codes = [] for num in range(int(num_start), int(num_end)): codes.append(code + str(num).zfill(6)) gift_card_service.update_bind_product(codes, product_id) return jsonify(Result().success())
def before_user(): check_login = current_app.config.get("CHECK_LOGIN") testing = current_app.config.get("TESTING") if check_login: return path = request.path allow_path = current_app.config.get("ALLOW_NOT_LOGIN") for allow in allow_path: if re.match(allow, path): return else: if current_app.config.get("TESTING"): if not 'user_id' in session: session["user_id"] = "5d83041c71a281581fe0b93b" return if not 'user_id' in session: app.logger.info("not login path %s" % path) return jsonify(Result().fail(code="user.not.login", msg="user not login"))
def create_gift_card(): 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")) code = data.get('code') password = data.get('password') areas = data.get('areas') name = data.get('name') mobile = data.get('mobile') address = data.get('address') save = OrdSave() 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.not.found")) if password != gift.password: return jsonify(Result().fail(code="gift.password.error")) if not gift.product_id: return jsonify(Result().fail(code="gift.product.relation", msg="gift card not bind to the product")) if gift.status != 1: return jsonify(Result().fail(code="gift.card.expire", msg="gift card expire or used")) save.gift_card_id = str(gift.id) save.gift_card_code = gift.code product = product_service.find_by_id(gift.product_id) if not product: return jsonify(Result().fail(code="product.not.exist", msg="product not exist")) gift_card_service.update_used(code, password) ord_product = OrdProduct() ord_product.product_id = str(product.id) ord_product.num = 1 ord_product.title = product.title ord_product.main_pic = product.main_pic save.add_product(ord_product) save.areas = areas save.name = name save.mobile = mobile save.address = address save.user_id = user_id save.status = const.ORD_WAIT_SEND id = ord_service.save(save) return jsonify(Result().success({"id": id}))
def _parse_results(self, soup) -> [Result]: html_list = soup.find('ol', {'id': 'results-list'}).findAll('li') results = [] for list_item in html_list: if not self._is_result(list_item): continue link = self._get_link(list_item) link_soup = self._open_result_link(link) results.append(Result( title=self._get_title(list_item), author=self._get_authors(list_item), date=self._get_year(list_item), link=link, pdf_link=self._get_pdf_link(list_item), cite_count=self._get_cite_count(link_soup), doi=self._get_doi(link_soup) )) return results
def html_to_result(self, html) -> [Result]: results = [] soup = BeautifulSoup(html, "html.parser") meta_articles = soup.findAll("div", {"class": "gs_r gs_or gs_scl"}) for meta_article in meta_articles: article_info = meta_article.find("div", {"class": "gs_ri"}) link_title = article_info.find("a") title = link_title.get_text() author = article_info.find("div", {"class": "gs_a"}).get_text() year = re.search(r'\d{4}', author).group() if re.search( r'\d{4}', author) else ResultConstants.NO_YEAR link = link_title["href"] additional_info = meta_article.find("div", {"class": "gs_or_ggsm"}) pdf_link = additional_info.find( "a")["href"] if additional_info else ResultConstants.NO_PDF result = Result(title=title, author=author, date=year, link=link, pdf_link=pdf_link, cite_count=self._get_cite_count(meta_article)) results.append(result) return results