def upload_img(request): img = request.FILES.get('image') if not all(img): return JsonResponse({'code': '-1', 'msg': 'no image'}) abs_path = '' try: # 存储文件 file_name = "%s.png" % (time.time() * 1000) # web_path = os.path.join(OUT, file_name) abs_path = os.path.join(ABS_OUT, file_name) with open(abs_path, "wb") as fp: for chunk in img.chunks(): fp.write(chunk) except Exception as msg: return JsonResponse({"code": -3, "msg": "Upload filed! Msg:%s" % msg}) options = { 'detect_direction': 'true', 'language_type': 'CHN_ENG', } # 调用通用文字识别接口 result = aipOcr.basicGeneral(get_file_content(abs_path), options) # print(json.dumps(result).decode("unicode-escape")) return JsonResponse(result)
def registerUser(request): response = {} if "username" not in request.GET or request.GET["username"] == '': response[RetCode_Key] = ErrorCode_LoginUserName return JsonResponse(response) if "password" not in request.GET or request.GET["password"] == '': response[RetCode_Key] = ErrorCode_LoginPassword return JsonResponse(response) username = request.GET["username"] password = request.GET["password"] Log.d(LOGTAG, 'registerUser, username: '******'registerUser, password: ' + password) try: user = RhUser.objects.get(username=username) except ObjectDoesNotExist: user = RhUser.objects.create_user(username=username, password=password, user_type=USER_TYPE_H5) if user is None: response[RetCode_Key] = ErrorCode_FailToRegisterUser return JsonResponse(response) response[RetCode_Key] = ErrorCode_OK return JsonResponse(response) response[RetCode_Key] = ErrorCode_UserExisted return JsonResponse(response)
def getUserFavoriteList(request): Log.d(LOGTAG, 'getUserFavoriteList') response = {} ''' response[RetCode_Key] = ErrorCode_OK response[RetCode_Data] = ['mm'] return JsonResponse(response) ''' # get uid from request uid = getUid(request, response) if response[RetCode_Key] != ErrorCode_OK: Log.e(LOGTAG, 'Request has error when get uid on changing user favorite rh!') return JsonResponse(response) Log.d(LOGTAG, 'uid: ' + str(uid)) favList = [] favDb = FavoriteDb(uid) response[RetCode_Key] = favDb.getFavoriteListForWeb(favList) response[RetCode_Data] = favList Log.d( LOGTAG, 'getUserFavoriteList, ret: ' + getErrorString(response[RetCode_Key]) + ', data: ' + str(response[RetCode_Data])) return JsonResponse(response)
def post(self, request, *args, **kwargs): # print(request.POST) print( request.POST.get("testData") ) # przychwytuje zmienna ze slownika json o nazwie data z jQuery w dashboard/test.html # below is python dictionary, not json if request.is_ajax(): if not (request.user.is_authenticated): data = { "works": False, } return JsonResponse(data, status=401) # data nizej to data wywolywane przez jquery w dashboard/test.html: # request.done(function(data){ # if (data.works){ data = { "works": True, "time": "%s <br> %s" % ("Super, drukuje", datetime.datetime.now()), } return JsonResponse(data) #python 'data' is being changed # into JSON (i w test.html widac to) ## dzieki czemu kontekst slownikowy data wyzej ## bedzie odczytany przez jquery w checkout/text.html ## data.time i data.works return HttpResponse('Checkout Test View Here!')
def changeUserFavoriteRh(request): Log.d(LOGTAG, 'changeUserFavoriteRh') response = {} if "rhId" not in request.GET or request.GET["rhId"] == '': response[RetCode_Key] = ErrorCode_Param return JsonResponse(response) if "f" not in request.GET or request.GET["f"] == '': response[RetCode_Key] = ErrorCode_Param return JsonResponse(response) f = (request.GET["f"] == 't') try: rhId = int(request.GET["rhId"]) rhId = Utils.get_rh_id_from_web_content(rhId) except ValueError: Log.e( LOGTAG, 'Request has error parameter of rhId when change user favorite rh!' ) response[RetCode_Key] = ErrorCode_Param return JsonResponse(response) # get uid from request uid = getUid(request, response) if response[RetCode_Key] != ErrorCode_OK: Log.e(LOGTAG, 'Request has error when get uid on changing user favorite rh!') return JsonResponse(response) Log.d(LOGTAG, 'uid: ' + str(uid)) Log.d(LOGTAG, 'rhId: ' + str(rhId)) Log.d(LOGTAG, 'favorite: ' + request.GET["f"]) favRecord = None try: favRecord = favorite.objects.get(uid=uid, rhId=rhId) except ObjectDoesNotExist: Log.d(LOGTAG, 'changeUserFavoriteRh, ObjectDoesNotExist') pass if favRecord is None: Log.d(LOGTAG, 'changeUserFavoriteRh, favRecord is None') if f: Log.d(LOGTAG, 'changeUserFavoriteRh, f') newFavRecord = favorite(uid=uid, rhId=rhId) newFavRecord.save() else: Log.d(LOGTAG, 'changeUserFavoriteRh, favRecord is not None') if not f: Log.d(LOGTAG, 'changeUserFavoriteRh, not f') favRecord.delete() response[RetCode_Key] = ErrorCode_OK return JsonResponse(response)
def weixinlogin_test(request): Log.e(LOGTAG, 'weixinlogin_test') response = {} if "code" not in request.GET or request.GET["code"] == '': response[RetCode_Key] = ErrorCode_WeixinLoginNoCode return JsonResponse(response) unionid = request.GET["code"] Log.e(LOGTAG, 'Weixin login, weixin code: ' + unionid) response = registerUserForWeixin(unionid) return JsonResponse(response)
def user_tasks(request, pk): """tasks=get_object_or_404(Task, pk=pk) form = UserForm(request.GET or None, instance=task) if form.is_valid(): """ data = User_Tasks.objects.filter(user_id=pk) return JsonResponse(list(data.values()), safe=False)
def form_valid(self, form): """ :param RelatedFormFactory form: :return: """ form.save() return JsonResponse()
def getRhDetail(request): if "rhid" not in request.GET: response = {} response[RetCode_Key] = str(ErroCode_RhIdNotInput) return JsonResponse(response) # get_data_from_rh_id(response, request.GET['rhid']) detail_query = RhDetailQuery(request.GET['rhid']) # userIp, clientType, userId, visitTime, location, function, param ipAddr = Utils.getIpAddress(request) ''' UserStat.addVisitRequest(request, 'rhdetail', "rhid=" + str(detail_query.getIntRhId())) ''' ret = detail_query.get_data_from_rh_id() return JsonResponse(ret)
def google_get_state_token(request, action_type_id, action_id): action_state = ActionState.objects.create( **{ 'action_type_id': action_type_id, 'action_id': action_id, 'data': request.GET }) return JsonResponse({'stat': 'ok', 'token': action_state.uuid})
def post(self, request, *args, **kwargs): if not (request.user.is_authenticated): return JsonResponse({}, status=401) user = request.user product_id = request.POST.get( "product_id" ) ##przejete z ajaxa na stonie product_detail.html na ktora wyrzuca ten View exists = Product.objects.filter(id=product_id).exists() if not exists: return JsonResponse({}, status=404) product_obj = Product.objects.filter(id=product_id).first() #na wypadek gdyby byl inny produkt o takim samym id; mozna tez tak: # try: # product_obj = Product.objects.filter(id=product_id) # except: # product_obj = Product.objects.filter(id=product_id).first() # credit card required ** # run transaction: trans_obj = Transaction.objects.create(user=request.user, product=product_obj, price=product_obj.get_price) my_products = MyProducts.objects.get_or_create(user=request.user)[0] my_products.products.add(product_obj) download_link = product_obj.get_download() preview_link = download_link + "?preview=True" data = { "download": download_link, "preview": preview_link, } # data = { # "works":True, # "time":datetime.datetime.now(), # } return JsonResponse( data ) #python 'data' converted into JSON (w test.html widac, http://127.0.0.1:8000/test/)
def testdb(request): # 初始化 response = "" response1 = "" # 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM list = rh.objects.all() response = list[0].rh_name return JsonResponse({'rh_name': response, 'ret': 'ok'})
def trends(request): tokens = Client.objects.get(user=request.user.id) access_token = tokens.twitter_oauth_token access_token_secret = tokens.twitter_oauth_secret auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) trends1 = api.trends_place(23424863) data = trends1[0] trends = data['trends'] names = [trend['name'] for trend in trends] trendsName = ' '.join(names) return JsonResponse(trendsName, safe=False)
def currcity(request): city = '' if 'city' in request.POST: city = request.POST['city'] area = getCurrArea(city) if area is None: area = [] request.session['geolocation_privince'] = area['privince'] request.session['geolocation_city'] = area['city'] request.session['has_located'] = "y" return JsonResponse(json.dumps(area), content_type="application/json")
def monitoreo_ajax(request, pk): logging.info('monitoreo_ajax: Se intento una petición por el método: ' + request.method) try: id_srv = pk servidor = Servidor.objects.get(estado=True, id=id_srv) except: logging.error('monitoreo: No se encontró el servidor: ' + id_srv) return render(request, "monitoreo.html", {'error': True}) datos_servidor = api.solicitar_datos_srv(id_srv, servidor) return JsonResponse({ 'status': 200, 'data': datos_servidor, 'message': 'Ocurrió un error al procesar solicitud', })
def citylist(request): privince = "" city = "" if 'privince' in request.POST: privince = request.POST['privince'] if 'city' in request.POST: city = request.POST['city'] area_list = getAreaList(privince, city) if area_list is None: area_list = [] return JsonResponse(area_list)
def getUid(request, response): if "etype" not in request.GET: Log.e(LOGTAG, 'Request has no parameter of etype when get uid from request!') response[RetCode_Key] = ErrorCode_Param return -1 if request.GET["etype"] == ETYPE_H5: if request.session.get(SESSION_KEY_UID, default=None) is None: response[RetCode_Key] = ErrorCode_NotLogin return -1 uid = request.session[SESSION_KEY_UID] elif request.GET["etype"] == ETYPE_WEAPP: # TODO, should not only use unionid to identify user's session # we should add session id to identify it if "uid" not in request.GET or request.GET["uid"] == '': Log.e( LOGTAG, 'Request has no parameter of uid when get uid from request for weapp!' ) response[RetCode_Key] = ErrorCode_Param return JsonResponse(response) # unionid = request.GET["unionid"] # TODO, FIXME # SessionManager.getUid(unionid) # uid = getUidFromUnionidForWeixin(response, unionid) # if response[RetCode_Key] != ErrorCode_OK: # return -1 try: uid = int(request.GET["uid"]) except ValueError: Log.e(LOGTAG, 'Request has error parameter of uid!') response[RetCode_Key] = ErrorCode_Param return JsonResponse(response) response[RetCode_Key] = ErrorCode_OK return uid
def post(self, request, *args, **kwargs): if not (request.user.is_authenticated): return JsonResponse({}, status=401) user=request.user product_id = request.POST.get("product_id") rating_value = request.POST.get("rating_value") exists = Product.objects.filter(id=product_id).exists() if not exists: return JsonResponse({},status=404) product_obj = Product.objects.filter(id=product_id).first() rating_obj, rating_obj_created = ProductRating.objects.get_or_create(user=user, product=product_obj) try: rating_obj = ProductRating.objects.get(user=user, product=product_obj) except ProductRating.MultipleObjectsReturned: rating_obj = ProductRating.objects.filter(user=user, product=product_obj).first() except: rating_obj = ProductRating() rating_obj.user = user rating_obj.product = product_obj rating_obj.rating = int(rating_value) try: myproducts = user.myproducts.products.all() if product_obj in myproducts: rating_obj.verified = True rating_obj.save() except: pass data = { "success":True } return JsonResponse(data)
def areaList(request): prov = "" city = "" if 'prov' in request.GET: prov = request.GET['prov'] if 'city' in request.GET: city = request.GET['city'] area_list = AreaQuery.getAreaList(prov, city) if area_list is None: area_list = [] # for python3.0 area_list_1 = [] for elem in area_list: area_list_1.append(elem) return JsonResponse(area_list_1)
def get_players(): player_stats = PlayerStats.objects() if request.args.get('players'): player_names = request.args.get('players').split(',') player_ids = [] for name in player_names: if " " in name: name_parts = name.split(' ') first_name = name_parts[0] last_name = name_parts[1] players = Player.objects(first_name__icontains=first_name, last_name__icontains=last_name) else: players = Player.objects( Q(first_name__icontains=name) | Q(last_name__icontains=name)) player_ids.extend([player.id for player in players]) player_stats = player_stats(player__in=player_ids) player_stats = player_stats[: 100] # limit number of results to at most 100 for now stats_json = [json.loads(stats.to_json()) for stats in player_stats] return JsonResponse(json.dumps(stats_json))
def login(request): response = {} if "username" not in request.GET or request.GET["username"] == '': response[RetCode_Key] = ErrorCode_LoginUserName return JsonResponse(response) if "password" not in request.GET or request.GET["password"] == '': response[RetCode_Key] = ErrorCode_LoginPassword return JsonResponse(response) username = request.GET["username"] password = request.GET["password"] Log.d(LOGTAG, 'login, username: '******'login, password: '******'login, uid: ' + str(uid)) return JsonResponse(response)
def get_player(object_id): player = Player.objects(id=object_id).get() return JsonResponse(player.to_json())
def weixinlogin(request): Log.d(LOGTAG, 'Weixin login!') response = {} if "code" not in request.GET or request.GET["code"] == '': response[RetCode_Key] = ErrorCode_WeixinLoginNoCode return JsonResponse(response) weixinCode = request.GET["code"] Log.d(LOGTAG, 'Weixin login, weixinCode: ' + weixinCode) # url = 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code # url = 'http://www.baidu.com' url = ('https://api.weixin.qq.com/sns/jscode2session?appid=' + WEIXIN_APPID + '&secret=' + WEIXIN_SECRET + '&js_code=' + weixinCode + '&grant_type=authorization_code') Log.d(LOGTAG, 'Weixin login, url: ' + url) try: response = urllib.request.urlopen(url, timeout=5.0) except urllib.error.URLError as e: if isinstance(e.reason, socket.timeout): response[RetCode_Key] = ErrorCode_WeixinServerError Log.e( LOGTAG, 'Fail to requesting unionid of weixin on timeout, code: ' + weixinCode) return JsonResponse(response) if response is None: response = {} response[RetCode_Key] = ErrorCode_WeixinServerError Log.e( LOGTAG, 'Fail to requesting unionid of weixin with none response, code: ' + weixinCode) return JsonResponse(response) # wx0075bca25e961250 # b96f3b34e596f414744d56cd8081d2ed data_1 = response.read() Log.d(LOGTAG, 'Success to requesting unionid of weixin, data: ' + str(data_1)) response = json.loads(data_1) Log.d( LOGTAG, 'Success to requesting unionid of weixin, data.map: ' + str(response)) if 'openid' not in response or response[ 'openid'] == '' or 'session_key' not in response or response[ 'session_key'] == '': response = {} response[RetCode_Key] = ErrorCode_WeixinServerError Log.e( LOGTAG, 'Fail to requesting openid or sesseion_key of weixin, code: ' + weixinCode) return JsonResponse(response) # FIXME unionid = response['openid'] ret = registerUserForWeixin(unionid) if ret[RetCode_Key] == ErrorCode_UserExisted: ret[RetCode_Key] = ErrorCode_OK return JsonResponse(ret)
def logout(request): Log.d(LOGTAG, 'logout') request.session.clear() return JsonResponse({RetCode_Key: ErrorCode_OK})
def get_stats(object_id): stats = PlayerStats.objects(id=object_id).get() return JsonResponse(stats.to_json())
def form_invalid(self, form): return JsonResponse({}, status=JsonResponse.ErrorStatus(form.errors))
def get(self, request, *args, instance=None, **kwargs): # return JsonResponse( self.form_factory(instance or (args and args[0] or None)).serialize())
def showRhList(request): # return JsonResponse('hello') Log.m(LOGTAG, 'showRhList, start', True) query_param = QueryParam() if "prov" in request.GET: query_param.province = request.GET['prov'] if "city" in request.GET: query_param.city = request.GET['city'] if "area" in request.GET: query_param.area = request.GET['area'] if "min_price" in request.GET: try: query_param.minprice = int(request.GET['min_price']) except ValueError: pass if "max_price" in request.GET: try: query_param.maxprice = int(request.GET['max_price']) except ValueError: pass if "min_bed" in request.GET: try: query_param.minbed = int(request.GET['min_bed']) except ValueError: pass if "max_bed" in request.GET: try: query_param.maxbed = int(request.GET['max_bed']) except ValueError: pass if "type" in request.GET: query_param.str_type = request.GET['type'] if "prop" in request.GET: query_param.prop = request.GET['prop'] if "page" in request.GET: try: query_param.page = int(request.GET['page']) except ValueError: pass if "searchKey" in request.GET: query_param.searchKey = request.GET['searchKey'] Log.m(LOGTAG, 'showRhList, start-1') response = {} if "favList" in request.GET: Log.i(LOGTAG, 'Requesting user favorite rh list!') # get uid from request uid = getUid(request, response) if response[RetCode_Key] != ErrorCode_OK: Log.e( LOGTAG, 'Request has error when get uid on changing user favorite rh!') return JsonResponse(response) if uid is None: Log.e(LOGTAG, 'User not login in!') response[RetCode_Key] = ErrorCode_NotLogin response[RetCode_Data] = [] return JsonResponse(response) query_param.favList = (request.GET["favList"] == 't') Log.i( LOGTAG, 'Requesting user favorite rh, favList: ' + str(query_param.favList)) query_param.uid = uid Log.i(LOGTAG, 'Requesting user favorite rh, uid: ' + str(query_param.uid)) Log.m(LOGTAG, 'showRhList, start-2') # FIXME rh_list_query = RhListQuery(query_param) response = rh_list_query.get_rh_list() Log.m(LOGTAG, 'showRhList, end') return JsonResponse(response)
def get_players(): player_objs = Player.objects() players_json = [json.loads(player.to_json()) for player in player_objs] return JsonResponse(json.dumps(players_json))