def check_update(request): url = 'https://gitee.com/api/v5/repos/zmister/MrDoc/tags' resp = requests.get(url, timeout=5).json() return JsonResponse({'status': True, 'data': resp[-1]})
def companies(request): companies_list = Company.objects.all() companies_list_json = [company.to_json() for company in companies_list] return JsonResponse(companies_list_json, safe=False)
def user_center_menu(request): menu_data = [ { "id": 1, "title": _("我的概览"), "type": 1, "icon": "layui-icon layui-icon-console", "href": reverse('manage_overview'), }, { "id": "my_project", "title": _("我的文集"), "icon": "layui-icon layui-icon-component", "type": 0, "href": "", "children": [ { "id": "manage_project", "title": _("文集管理"), "icon": "layui-icon layui-icon-console", "type": 1, "openType": "_iframe", "href": reverse('manage_project') }, { "id": "manage_colla_self", "title": _("我的协作"), "icon": "layui-icon layui-icon-console", "type": 1, "openType": "_iframe", "href": reverse('manage_pro_colla_self') }, { "id": "import_project", "title": _("导入文集"), "icon": "layui-icon layui-icon-console", "type": 1, "openType": "_iframe", "href": reverse('import_project') }, ] }, { "id": "my_doc", "title": _("我的文档"), "icon": "layui-icon layui-icon-file-b", "type": 0, "href": "", "children": [ { "id": "doc_manage", "title": _("文档管理"), "icon": "layui-icon layui-icon-face-smile", "type": 1, "openType": "_iframe", "href": reverse("manage_doc") }, { "id": "doc_template", "title": _("文档模板"), "icon": "layui-icon layui-icon-face-cry", "type": 1, "openType": "_iframe", "href": reverse("manage_doctemp") }, { "id": "doc_tag", "title": _("文档标签"), "icon": "layui-icon layui-icon-face-cry", "type": 1, "openType": "_iframe", "href": reverse("manage_doc_tag") }, { "id": "doc_share", "title": _("我的分享"), "icon": "layui-icon layui-icon-face-cry", "type": 1, "openType": "_iframe", "href": reverse("manage_doc_share") }, { "id": "doc_recycle", "title": _("文档回收站"), "icon": "layui-icon layui-icon-face-cry", "type": 1, "openType": "_iframe", "href": reverse("doc_recycle") } ] }, { "id": "my_fodder", "title": _("我的素材"), "icon": "layui-icon layui-icon-upload-drag", "type": 0, "href": "", "children": [ { "id": "my_img", "title": _("我的图片"), "icon": "layui-icon layui-icon-face-smile", "type": 1, "openType": "_iframe", "href": reverse("manage_image") }, { "id": "my_attachment", "title": _("我的附件"), "icon": "layui-icon layui-icon-face-cry", "type": 1, "openType": "_iframe", "href": reverse("manage_attachment") }, ] }, { "id": "my_collect", "title": _("我的收藏"), "icon": "layui-icon layui-icon-star", "type": 1, "openType": "_iframe", "href": reverse("manage_collect") }, { "id": "self_settings", "title": _("个人管理"), "icon": "layui-icon layui-icon-set-fill", "type": 0, "href": "", "children": [ { "id": 601, "title": _("个人设置"), "icon": "layui-icon layui-icon-face-smile", "type": 1, "openType": "_iframe", "href": reverse("manage_self") }, { "id": 602, "title": _("Token管理"), "icon": "layui-icon layui-icon-face-cry", "type": 1, "openType": "_iframe", "href": reverse("manage_token") }, ] }, { "id": "user_manual", "title": _("使用手册"), "icon": "layui-icon layui-icon-template-1", "type": 1, "openType": "_blank", "href": "https://doc.mrdoc.pro/project-54/", } # { # "id": "common", # "title": "使用帮助", # "icon": "layui-icon layui-icon-template-1", # "type": 0, # "href": "", # "children": [{ # "id": 701, # "title": "安装说明", # "icon": "layui-icon layui-icon-face-smile", # "type": 1, # "openType": "_iframe", # "href": "http://mrdoc.zmister.com/project-7/" # }, { # "id": 702, # "title": "使用说明", # "icon": "layui-icon layui-icon-face-smile", # "type": 1, # "openType": "_iframe", # "href": "http://mrdoc.zmister.com/project-54/" # }] # } ] return JsonResponse(menu_data,safe=False)
def vacancies(request): vacancies_list = Vacancy.objects.all() vacancies_list_json = [vacancy.to_json() for vacancy in vacancies_list] return JsonResponse(vacancies_list_json, safe=False)
def vacancy(request, id): vacancies_list = Vacancy.objects.all() for vacancy in vacancies_list: if vacancy.id == id: return JsonResponse(vacancy.to_json(), safe=False)
def polygon_all_tickers(request): default_host = 'https://api.polygon.io' polygon_url = default_host + '/vX/reference/tickers?limit=500&apiKey=' apiKey = 'u8arVdihlX_6p_pRuvRUwa94YmI4Zrny' url = polygon_url + apiKey limit_query_times = 30 ncount = 0 next_page_path = '' rest = 0 all_tickers = [] with RESTClient(auth_key='u8arVdihlX_6p_pRuvRUwa94YmI4Zrny') as client: for t in range(limit_query_times): if ncount == 0: rep = requests.get(url).json() next_page_path = rep['next_page_path'] all_tickers.extend(rep['results']) else: url = default_host + next_page_path rep = requests.get(url).json() all_tickers.extend(rep['results']) if rest > 0 and 'next_page_path' in rep: next_page_path = rep['next_page_path'] else: break print(next_page_path) rest = limit_query_times - ncount ncount += 1 for t in all_tickers: cik = t['cik'] if 'cik' in t else '' composite_figi = t[ 'composite_figi'] if 'composite_figi' in t else '' share_class_figi = t[ 'share_class_figi'] if 'share_class_figi' in t else '' currency_name = t[ 'currency_name'] if 'currency_name' in t else '' ticker = Ticker(symbol=t['ticker'], name=t['name'], market=t['market'], locale=t['locale'], active=t['active'], cik=cik, composite_figi=composite_figi, share_class_figi=share_class_figi, currency_name=currency_name, last_updated_utc=t['last_updated_utc'], created_at=datetime.now().strftime('%Y-%m-%d')) try: ticker.save() print(f"Ticker:{ticker} detail is saved".format( ticker=t['ticker'])) except: pass try: rep_detail = client.reference_ticker_details( symbol=t['ticker']) if rep_detail.sector is not None: tickerS = Ticker.objects.get(symbol=t['ticker']) ticker_detail = TickerDetail( ticker=tickerS, exchange=rep_detail.exchange, exchangeSymbol=rep_detail.exchange, industry=rep_detail.industry, sector=rep_detail.sector, tags=rep_detail.tags, similar=rep_detail.similar, list_date=rep_detail.listdate, updated_date=datetime.strptime( rep_detail.updated, '%d/%M/%Y').strftime('%Y-%m-%d')) ticker_detail.save() except: pass return JsonResponse({'message': 'query all tickers from Polygon.io'}, status=status.HTTP_200_OK)
def handle_post_rename_folder(self, data): folder = Folder.objects.get(pk=data["id"]) folder.name = data["name"] folder.save(update_fields=("name", )) return JsonResponse({"success": True, "message": _("Folder renamed.")})
def movie_info(request, id): data = Client().get_movie(id = int(id), min_update_level = INFO_UPDATE_LEVEL, force_update = TMDB_FORCE_UPDATE) return JsonResponse(data, safe=False)
def post(self, request, *args, **kwargs): cart = self.get_object() cart.deleted = True cart.save() return JsonResponse({"status": "success"}, status=200)
def logout(request): try: del request.session["user_id"] except Exception as e: logger.error(repr(e)) return JsonResponse(success)
def preload(self, request, params={}): self.data = CourseService().search(self.form) preloadList = [] for x in self.data: preloadList.append(x.to_json()) return JsonResponse({"preloadList": preloadList})
def need_login_msg(request): return JsonResponse(user_not_login)
def access_error(request): return JsonResponse(user_access_error)
def create_chapter_request(request): ''' 新たなチャプターを作成する ''' # POSTを受け取る payload = request.POST text = payload["text"] cropping_x = float(payload["cropping_x"]) cropping_y = float(payload["cropping_y"]) cropping_w = float(payload["cropping_w"]) cropping_h = float(payload["cropping_h"]) print(payload) image = request.FILES["original_image"] content_type = image.content_type # セッション情報の取得 if "user_id" in payload.keys(): user_id = int(payload["user_id"]) else: user_id = int(request.user.id) # book_idを取得 if "mybook_id" in request.session: book_id = int(request.session["mybook_id"]) else: return JsonResponse({"code" : 400, "comment" : "mybook_idが見つかりません"}) # 画像の保存先を決める if content_type not in ["image/jpeg", "image/png"]: content_type = "image/jpeg" if content_type == "image/png": ext = "png" else: ext = "jpg" temporal_image_path = None try: temporal_image_path = image.temporary_file_path() print("temporal path exists") print(temporal_image_path) except: print("temporal path not exist") image_basename = generate_basename(key=str(user_id)+"newchapter", ext=ext) image_url = fname_cloud(image_basename) # 画像を読み込み if temporal_image_path is None: # もしオンメモリデータだったら、画像にして保存 temporal_image_path = generate_temporal_path(image_basename) with open(temporal_image_path, 'wb') as f: f.write(image.read()) im = Image.open(temporal_image_path) # exifに基づいて修正 im_modify = modify_by_EXIF(im) if im_modify is not None: im = im_modify im_crop = im.crop((cropping_x, cropping_y, cropping_x+cropping_w, cropping_y+cropping_h)) # スマホから送信すると"**.upload"という拡張子になることがあるので対策 if get_normalized_ext(temporal_image_path.split(".")[-1], restriction="image") is None: temporal_image_path = ".".join(temporal_image_path.split(".")[:-1] + [ext]) # 画像をトリミング if ext == "jpg": im_crop.save(temporal_image_path, quality=100) else: im_crop.save(temporal_image_path) # アップロード bucket.upload_file( temporal_image_path, image_basename, ExtraArgs={"ContentType": content_type} ) if os.path.exists(temporal_image_path): os.remove(temporal_image_path) print("uploaded image") # レコードを保存 record_Book = Book.objects.get(id=book_id) record_Chapter = Chapter( book = record_Book, title = text, thumb_url = image_url, ) record_Chapter.save() print("saved chapter") return JsonResponse({"code" : 200})
def json_lista_evento(request, id_usuario): usuario = User.objects.get(id=id_usuario) evento = Evento.objects.filter(usuario=usuario).values('id', 'titulo') return JsonResponse(list(evento), safe=False)
def get(self, request: Request) -> JsonResponse: """ :param request: :return: """ return JsonResponse({})
def polygon_all_tickers_v2(request): tickers_all_detail.delay() return JsonResponse({'message': 'send to background'}, status=status.HTTP_200_OK)
def get(self, request: Request) -> JsonResponse: return JsonResponse( {"Message": "Method Get Is Not Allowed While APi is working"})
def handle_get_folders(self, data): root_folders = get_cached_trees(Folder._tree_manager.all()) return JsonResponse( {"rootFolder": _filer_folder_to_json_dict(None, root_folders)})
def post(self, request: Request) -> JsonResponse: try: userid = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if userid == 0: self.logger.error("Error in changePassword API token: ") return JsonResponse( create_failure(400, 'invalid Token', 'Fail')) except Exception as e: self.logger.error("Error in changePassword API: " + str(e)) return JsonResponse( create_failure(400, 'Please provide valid Token', 'Fail')) try: email = request.data['email'] if not email: self.logger.error("invalid email") return JsonResponse( create_failure(400, 'provide valid email', 'Fail')) except Exception as e: self.logger.error("invalid email" + str(e)) return JsonResponse(create_failure(400, 'provide email', 'Fail')) try: oldPassword = request.data['old_password'] if not oldPassword: self.logger.error("invalid password") return JsonResponse( create_failure(400, 'provide valid old password', 'Fail')) userInfo = Userlogindetails.objects.get(emailaddress=email) self.logger.info(userInfo.password) if userInfo.password != (oldPassword): self.logger.error("invalid password") return JsonResponse( create_failure(400, 'invalid old password', 'Fail')) except Exception as e: self.logger.error("invalid password." + str(e)) return JsonResponse( create_failure(400, 'provide valid old password', 'Fail')) try: newPassword = request.data['new_password'] if not newPassword: self.logger.error("invalid new password") return JsonResponse( create_failure(400, 'provide valid new password', 'Fail')) except Exception as e: self.logger.error("invalid new password" + str(e)) return JsonResponse( create_failure(400, 'provide valid new password', 'Fail')) try: if newPassword == oldPassword: self.logger.error( "old password and new password should not be same") return JsonResponse( create_failure( 400, 'old password and new password should not be same', 'Fail')) except Exception as e: self.logger.error( "old password and new password should not be same" + str(e)) return JsonResponse( create_failure( 400, 'old password and new password should not be same', 'Fail')) try: currentTime = timezone.now() UserlogindetailsUpdate = Userlogindetails.objects.filter( emailaddress=email).update(password=newPassword, modifieddate=currentTime) if UserlogindetailsUpdate == 0: return JsonResponse( create_failure(204, 'Failed to update password', 'Fail')) except Exception as e: self.logger.error("invalid email" + str(e)) return JsonResponse( create_failure(500, 'Failed to update password', 'Fail')) return JsonResponse( create_success("Password Updated Successfully!", []))
def handle_post_rename_file(self, data): file = File.objects.get(pk=data["id"]) file.name = data["name"] file.save(update_fields=("name", )) return JsonResponse({"success": True, "message": _("File renamed.")})
def product_detail(request, id): try: product = Product.objects.get(id=id) return JsonResponse(product.to_json()) except Product.DoesNotExist as e: return JsonResponse({'error': 'there is no product'})
def company(request, id): companies_list = Company.objects.all() for company in companies_list: if company.id == id: return JsonResponse(company.to_json(), safe=False)
def category_list(request): categories = Category.objects.all() json_categories = [c.to_json() for c in categories] return JsonResponse(json_categories, safe=False)
def vacancies_top(request): vacancies_list = Vacancy.objects.order_by("-salary")[:10] vacancies_list_json = [vacancy.to_json() for vacancy in vacancies_list] return JsonResponse(vacancies_list_json, safe=False)
def category_detail(request, id): try: category = Category.objects.get(id=id) return JsonResponse(category.to_json()) except Category.DoesNotExist as e: return JsonResponse({'error': 'there is no category'})
def form_invalid(self, form): return JsonResponse({ 'error': ugettext("Upload failed"), 'debug': form.errors })
def product_list(request): products = Product.objects.all() json_products = [p.to_json() for p in products] return JsonResponse(json_products, safe=False)
def logout_user(request): logout(request) return JsonResponse({ "status": 0 })
def admin_doc(request): if request.method == 'GET': # 文集列表 project_list = Project.objects.all() # 自己创建的文集列表 # 文档数量 # 已发布文档数量 published_doc_cnt = Doc.objects.filter(status=1).count() # 草稿文档数量 draft_doc_cnt = Doc.objects.filter(status=0).count() # 所有文档数量 all_cnt = published_doc_cnt + draft_doc_cnt return render(request, 'app_admin/admin_doc.html', locals()) elif request.method == 'POST': kw = request.POST.get('kw', '') project = request.POST.get('project', '') status = request.POST.get('status', '') if status == '-1': # 全部文档 q_status = [0, 1] elif status in ['0', '1']: q_status = [int(status)] else: q_status = [0, 1] if project == '': project_list = Project.objects.all().values_list( 'id', flat=True) # 自己创建的文集列表 q_project = list(project_list) else: q_project = [project] page = request.POST.get('page', 1) limit = request.POST.get('limit', 10) # 没有搜索 if kw == '': doc_list = Doc.objects.filter( status__in=q_status, top_doc__in=q_project).order_by('-modify_time') # 有搜索 else: doc_list = Doc.objects.filter( Q(content__icontains=kw) | Q(name__icontains=kw), status__in=q_status, top_doc__in=q_project).order_by('-modify_time') # 文集列表 project_list = Project.objects.filter( create_user=request.user) # 自己创建的文集列表 colla_project_list = ProjectCollaborator.objects.filter( user=request.user) # 协作的文集列表 # 文档数量 # 已发布文档数量 published_doc_cnt = Doc.objects.filter(create_user=request.user, status=1).count() # 草稿文档数量 draft_doc_cnt = Doc.objects.filter(create_user=request.user, status=0).count() # 所有文档数量 all_cnt = published_doc_cnt + draft_doc_cnt # 分页处理 paginator = Paginator(doc_list, limit) page = request.GET.get('page', page) try: docs = paginator.page(page) except PageNotAnInteger: docs = paginator.page(1) except EmptyPage: docs = paginator.page(paginator.num_pages) table_data = [] for doc in docs: item = { 'id': doc.id, 'name': doc.name, 'parent': Doc.objects.get( id=doc.parent_doc).name if doc.parent_doc != 0 else '无', 'project_id': Project.objects.get(id=doc.top_doc).id, 'project_name': Project.objects.get(id=doc.top_doc).name, 'status': doc.status, 'editor_mode': doc.editor_mode, 'open_children': doc.open_children, 'create_user': doc.create_user.username, 'create_time': doc.create_time, 'modify_time': doc.modify_time } table_data.append(item) resp_data = { "code": 0, "msg": "ok", "count": doc_list.count(), "data": table_data } return JsonResponse(resp_data)