예제 #1
0
def ajax_4(request):
    """
    浇水成功提交积分上去
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    user_id = request.POST.get('openid', '')
    source_id = request.POST.get('source_id', '')
    if user_id:
        user = User.objects.get(openid=user_id)
        if user_id == source_id:
            type = 0
        else:
            type = 3
        Tree(owner=user, tree_name=user.tree_name, count=user.count, type=type,
             action_time=time.time(), source_id=source_id,
             content=User.objects.get(openid=source_id).nickname+'给树木浇水了').save()

        user.count = user.count + 1000
        if source_id:
            try:
                friend = user.friends.get(openid=source_id)
            except ObjectDoesNotExist:
                friend = 0
            if friend != 0:
                user.friends.add(User.objects.get(openid=source_id))  # 通过朋友圈啊什么的浇水,自己浇水的时候自己是自己的朋友
        user.save()
        ret = '1'
    else:
        ret = '2'
    response.write(ret)
    return response
예제 #2
0
파일: views.py 프로젝트: q7940/sound
def register(request):
    """
    注册处理事件
    :param request:注册请求
    :return:
        ①result: '0'表示成功, '1'表示用户名重名, '2'表示未知错误,可能昵称/邮箱/密码为空,可能传输出错
        ②
    """
    # 回复
    response = HttpResponse()
    response['Content-Type'] = 'application/json'

    if request.method == 'POST':
        # 获取客户端信息
        nickname = request.POST.get('userName', '')
        password = request.POST.get('userCode', '')
        avatar = request.POST.get('avatar', '')

        if nickname and password:
            try:
                user = User.objects.get(nickname=nickname)
                result = '1'
            except ObjectDoesNotExist:
                user = User(nickname=nickname, mail='nomail', password=password, create_time=time.time(),
                            action_time=time.time())
                user.save()
                result = '0'
        else:
            result = '2'
    else:
        result = '-1'

    response.write(result)
    response.write(fetch_recommend())  # 返回首页信息
    return response
예제 #3
0
파일: views.py 프로젝트: isergey/libcms
def watch(request):
    response = HttpResponse(status=200)
    session = request.COOKIES.get('_sc', None)

    if not session:
        session = uuid.uuid4().hex
        response.set_cookie('_sc', session, max_age=60 * 60 * 24 * 365)

    http_referer = request.META.get('HTTP_REFERER', None)
    if not http_referer:
        return response

    url_parts = urlparse(http_referer)
    path_parts = utils.strip_path(url_parts.path)
    if len(path_parts) > 1:
        path = path_parts[1]
    else:
        path = path_parts[0]
    ignore = False

    query = url_parts.query

    url_hash = hashlib.md5((path + query).encode('utf-8')).hexdigest()

    before = (datetime.datetime.now() - datetime.timedelta(minutes=URL_TIMEOUT))
    # if models.PageView.objects.filter(datetime__gt=before, session=session, url_hash=url_hash).exists():
    #     ignore = True

    user = None
    if request.user.is_authenticated():
        user = request.user
    if session and not ignore:
        models.log_page_view(path=path, query=query, url_hash=url_hash, session=session, user=user)

    return response
예제 #4
0
def complaint_csv(modeladmin, request, queryset):
    response = HttpResponse(mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=complaints.csv"
    writer = csv.writer(response, csv.excel)
    response.write(u"\ufeff".encode("utf8"))  # BOM (optional...Excel needs it to open UTF-8 file properly)
    writer.writerow(
        [
            smart_str(u"ID"),
            smart_str(u"MESSAGE ID"),
            smart_str(u"TIMESTAMP"),
            smart_str(u"MAIL FROM"),
            smart_str(u"MAIL TO"),
            smart_str(u"USERAGENT"),
            smart_str(u"COMPLAINT TYPE"),
            smart_str(u"ARRIVAL DATE"),
        ]
    )
    for obj in queryset:
        writer.writerow(
            [
                smart_str(obj.pk or ""),
                smart_str(obj.sns_messageid or ""),
                smart_str(obj.mail_timestamp or ""),
                smart_str(obj.mail_from or ""),
                smart_str(obj.address or ""),
                smart_str(obj.useragent or ""),
                smart_str(obj.feedback_type or ""),
                smart_str(obj.arrival_date or ""),
            ]
        )
    return response
예제 #5
0
def get_response(request):
	if request.method == 'POST':
		try:
			task_id = request.POST.get('task_id', '')
			institution = request.POST.get('institution', '')
			proceso = request.POST.get('proceso','')
		
			filename1 = path + "ERRORES_" + proceso + "_" + institution + "_" +  task_id + ".txt"
			filename2 =  path + "CORRECTOS_" + proceso + "_" + institution + "_" +  task_id + ".txt"
			
			in_memory = StringIO()  
			zip = ZipFile(in_memory, "w")
				
			zip.write(filename1)
			zip.write(filename2)
			
			for file in zip.filelist:  
				file.create_system = 0      
			  
			zip.close()  
			rand = ''.join(random.choice(string.ascii_lowercase	+	string.digits)	for	x	in	range(6))
			nombre_archivo = institution  + "_" + rand + "_" + proceso + ".zip" 
			response = HttpResponse(content_type="application/zip")
			response['Content-Disposition'] = 'attachment; filename=' + nombre_archivo  

			in_memory.seek(0)      
			response.write(in_memory.read()) 
			
			os.remove(filename1)
			os.remove(filename2)
			
		except Exception,e:
			error = "ERROR: Se ha generado un error de sistema;Detalles: " + str(e)
			return HttpResponse(error)
예제 #6
0
파일: views.py 프로젝트: q7940/sound
def login(request):
    """
    用户登陆事件
    :param request:登陆请求
    :return:
        ①result: 返回码, '0'表示成功 '1'表示用户不存在 '2'表示用户密码错误 '3'表示未知错误
        ②info:dict数据,登陆成功返回的用户信息就保存在这个json里面了
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    result = '3'

    if request.method == 'POST':
        # 获取客户端信息
        nickname = request.POST.get('userName', '')
        password = request.POST.get('password', '')
        if nickname and password:
            try:
                # 用户存在
                user = User.objects.get(nickname=nickname)
                if user.password == password:
                    # 用户密码正确
                    result = '0'
                else:
                    result = '-1'
            except ObjectDoesNotExist:
                result = '-1'
    response.write(result)
    response.write(fetch_recommend())
    return response
예제 #7
0
def save_workspace(request):
    data = request.POST["my_data"]
    response = HttpResponse(mimetype="text/plain")
    response.write(data)
    date = datetime.datetime.now().strftime("%Y-%m-%d-T-%H-%M-%S")
    response["Content-Disposition"] = "attachment; filename=%s-%s.cdOnline" % ("workspace", date)
    return response
예제 #8
0
def new_venue_ajax_image(request,idnum):
	try:
		venue = Venue.objects.get(id=idnum)
		form = VenueImageForm(request.POST,request.FILES)
		if form.is_valid():
			new = VenueImage()
			new.image = form.cleaned_data["new_image"]
			new.caption = form.cleaned_data["caption"]
			new.venue = venue
			new.user = request.user
			new.save()
			images = squares(new.image,new)
			new.small_square.save(new.image.name,images[0],save=True)
			new.square.save(new.image.name,images[1],save=True)
			new.save()
			info = { "status": "success",
					 "image" : new.small_square.url,
					 "id" : new.id,
					 "caption" : new.caption }
			return HttpResponse(dumps(info),content_type="application/json")
		else:
			res = HttpResponse()
			res.status_code = 203
			print form.errors
			return res
	except Exception, e:
		print e
		res = HttpResponse()
		res.status_code = 500
		return res
예제 #9
0
    def preview(module_factory, conf_factory, dbm_factory, params):
        # 1. 通过参数解析配置
        preview_conf = params.get(ModuleCommon.p_preview_conf)
        if not preview_conf:
            return HttpResponse(u"参数错误")
        conf_dict = preview_conf.get(ModuleCommon.k_conf_dict)
        if not conf_dict:
            return HttpResponse(u"参数错误")
        params[ModuleCommon.k_conf_dict] = conf_dict

        path_route = preview_conf.get(ModuleCommon.p_path_route)
        if not path_route:
            return HttpResponse(u"参数错误")
        params[ModuleCommon.p_path_route] = path_route
        params["db_id"] = preview_conf.get("db_id")
        params["baike_id"] = preview_conf.get("baike_id")
        params["section"] = preview_conf.get("section")
        # 2. 跟view调用一致
        try:
            html_render = module_factory.base_loader.loader(module_factory, params)
            http_response = HttpResponse()
            html = module_factory.base_render.render(params.get(ModuleCommon.k_request), html_render)
            http_response.write(html)
            return http_response
        except Exception as info:
            return HttpResponse(u"参数错误")
예제 #10
0
파일: views.py 프로젝트: featman/SwitchGear
def switch_contral(request):
    response = HttpResponse()
    incident = {}
    try:
        if request.method == 'POST':
#            req = simplejson.loads(request.body)
            incident["suo_id"] = request.POST['suo_id']
            incident["gui_id"] = request.POST['gui_id']
            incident["switch_id"] = request.POST['switch_id']

            HOST='127.0.0.1'
            PORT=21590
            BUFSIZ=1024
            ADDR=(HOST,PORT)
            client=socket(AF_INET,SOCK_DGRAM)
            while True:
                client.sendto(incident)
                data,ADDR=client.recvfrom(BUFSIZ)
                if not data:
                    break

            client.close()

    except Exception,ex:
        print Exception,":",ex
        print "error"
        response.write("error")
        return response
예제 #11
0
def vote(request,image_id,value):
    cookie_key = "image_%s"%image_id
    days_expire = 1
    if request.is_ajax and not request.COOKIES.get(cookie_key):
        try:
            user_ip = get_client_ip(request)
            time_ago = datetime.datetime.now()-datetime.timedelta(days=days_expire)
            Vote.objects.get(user_ip=user_ip,created__gt=time_ago,image_id=image_id)
        except ObjectDoesNotExist:
                response = HttpResponse()
                try:
                    image = Image.objects.get(pk=image_id)
                except ObjectDoesNotExist:
                    return response
                vote = Vote()
                vote.value = 1 if value=='up' else -1
                vote.user_ip = user_ip
                vote.image = image
                vote.created = datetime.datetime.now()
                vote.save()
                image.rating = Vote.objects.filter(image=image)\
                    .aggregate(sum=Sum('value')).get('sum')
                image.save()
                recalc_sizes(image.miracle)
                image =Image.objects.get(id=image.pk)
                new_data = {'rating':image.rating,'id':image.pk,'size':image.size}
                new_data_encoded = json.dumps(new_data)
                response.write(new_data_encoded)
                set_cookie(response,cookie_key,True,days_expire)
                return response
    return HttpResponse()
예제 #12
0
파일: views.py 프로젝트: zhaizhifen/chain
    def post(request):
        name = Names.objects.get(username=request.user)
        ids = request.POST.getlist('id', None)
        idstring = []
        for i in ids:
            project = AssetInfo.objects.get(id=i).project
            project_obj = AssetProject.objects.get(projects=project)
            hasperm = name.has_perm('read_assetproject', project_obj)
            if hasperm:
                idstring.append(i)
        idstring2 = ','.join(idstring)
        qs = AssetInfo.objects.extra(where=['id IN (' + idstring2 + ')']).all()
        # return  render_to_csv_response(qs)
        fields = [
            field for field in Asset._meta.fields
            if field.name not in [
                'date_created'
            ]
        ]
        filename = 'assets.csv'
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="%s"' % filename
        response.write(codecs.BOM_UTF8)

        writer = csv.writer(
            response,
            dialect='excel',
            quoting=csv.QUOTE_MINIMAL)

        header = [field.verbose_name for field in fields]
        writer.writerow(header)
        for asset_ in qs:
            data = [getattr(asset_, field.name) for field in fields]
            writer.writerow(data)
        return response
예제 #13
0
def export_graph(conversion_function, graph_id, ext):
    response = HttpResponse(mimetype='application/gml')
    response['Content-Disposition'] = 'attachment; filename=graph.%s' % ext
    graph = get_whole_graph(graph_id)
    response_data = conversion_function(graph)
    response.write(response_data)
    return response
예제 #14
0
 def bounce_csv(self, request, queryset):
     # PREPARE
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment; filename=bounces.csv'
     writer = csv.writer(response, csv.excel)
     # PROCESS
     response.write(u'\ufeff'.encode('utf8'))  # BOM (optional...Excel needs it to open UTF-8 file properly)
     writer.writerow([
         smart_str(u"ID"),
         smart_str(u"MESSAGE ID"),
         smart_str(u"TIMESTAMP"),
         smart_str(u"MAIL FROM"),
         smart_str(u"MAIL TO"),
         smart_str(u"BOUNCE TYPE"),
         smart_str(u"BOUNCE SUBTYPE"),
         smart_str(u"REPORTING MTA"),
         smart_str(u"ACTION"),
         smart_str(u"STATUS"),
         smart_str(u"DIAGNOSTIC CODE")])
     for obj in queryset:
         writer.writerow([
             smart_str(obj.pk or ''),
             smart_str(obj.sns_messageid or ''),
             smart_str(obj.mail_timestamp or ''),
             smart_str(obj.mail_from or ''),
             smart_str(obj.address or ''),
             smart_str(obj.bounce_type or ''),
             smart_str(obj.bounce_subtype or ''),
             smart_str(obj.reporting_mta or ''),
             smart_str(obj.action or ''),
             smart_str(obj.status or ''),
             smart_str(obj.diagnostic_code or '')])
     # CONCLUDE
     return response
예제 #15
0
 def complaint_csv(self, request, queryset):
     # PREPARE
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment; filename=complaints.csv'
     writer = csv.writer(response, csv.excel)
     response.write(u'\ufeff'.encode('utf8'))  # BOM (optional...Excel needs it to open UTF-8 file properly)
     # PROCESS
     writer.writerow([
         smart_str(u"ID"),
         smart_str(u"MESSAGE ID"),
         smart_str(u"TIMESTAMP"),
         smart_str(u"MAIL FROM"),
         smart_str(u"MAIL TO"),
         smart_str(u"USERAGENT"),
         smart_str(u"COMPLAINT TYPE"),
         smart_str(u"ARRIVAL DATE")])
     for obj in queryset:
         writer.writerow([
             smart_str(obj.pk or ''),
             smart_str(obj.sns_messageid or ''),
             smart_str(obj.mail_timestamp or ''),
             smart_str(obj.mail_from or ''),
             smart_str(obj.address or ''),
             smart_str(obj.useragent or ''),
             smart_str(obj.feedback_type or ''),
             smart_str(obj.arrival_date or '')])
     # CONCLUDE
     return response
예제 #16
0
 def delivery_csv(self, request, queryset):
     # PREPARE
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment; filename=deliveries.csv'
     writer = csv.writer(response, csv.excel)
     # PROCESS
     response.write(u'\ufeff'.encode('utf8'))  # BOM (optional...Excel needs it to open UTF-8 file properly)
     writer.writerow([
         smart_str(u"ID"),
         smart_str(u"MESSAGE ID"),
         smart_str(u"TIMESTAMP"),
         smart_str(u"MAIL FROM"),
         smart_str(u"MAIL TO"),
         smart_str(u"SMTP RESPONSE"),
         smart_str(u"REPORTIN MTA")])
     for obj in queryset:
         writer.writerow([
             smart_str(obj.pk or ''),
             smart_str(obj.sns_messageid or ''),
             smart_str(obj.mail_timestamp or ''),
             smart_str(obj.mail_from or ''),
             smart_str(obj.address or ''),
             smart_str(obj.smtp_response or ''),
             smart_str(obj.reporting_mta or '')])
     # CONCLUDE
     return response
예제 #17
0
def export_student_list(modeladmin, request, queryset):
    import csv
    from django.utils.encoding import smart_str
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=nexteria_zoznam_studentov.csv'
    writer = csv.writer(response, csv.excel)
    response.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
    writer.writerow([
        smart_str(u"Meno"),
        smart_str(u"Priezvisko"),
        smart_str(u"Email"),
        smart_str(u"Telefon"),
        smart_str(u"Datum nar."),
        smart_str(u"Fakulta"),
        smart_str(u"Rok zaciatku"),
        smart_str(u"Level"),
        smart_str(u"Skolne"),
    ])

    for obj in queryset:
        writer.writerow([
            smart_str(obj.clovek.meno),
            smart_str(obj.clovek.priezvisko),
            smart_str(obj.clovek.email),
            smart_str(obj.clovek.telefon_cislo),
            smart_str(obj.datum_nar),
            smart_str(obj.fakulta),
            smart_str(obj.rok_zaciatku),
            smart_str(obj.level),
            smart_str(obj.skolne),
        ])
    return response
예제 #18
0
def ajax_10(request):
    """
    给别人吐槽
    :param request:
        注意此处的source_id是推送的人的id,就是谁触发事件的
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'text/javascript'
    user_id = request.POST.get('openid', '')
    source_id = request.POST.get('source_id', '')
    tucao_con = request.POST.get('tucao_con', '')
    ret = '0'
    if user_id and source_id and tucao_con:
        user = User.objects.get(openid=user_id)
        user.count = user.count - 8000
        user.save()
        tucao = Tree(owner=user, tree_name=user.tree_name, type=6, action_time=time.time(), read=False,
                    source_id=source_id, content=tucao_con)
        tucao.save()
        ret = '1'
    else:
        ret = '2'
    response.write(ret)
    return response
예제 #19
0
def new_venue_image(request,idnum):
	try:
		venue = Venue.objects.get(id=idnum)
		form = VenueImageForm(request.POST,request.FILES)
		if form.is_valid():
			new = VenueImage()
			new.image = form.cleaned_data["new_image"]
			new.caption = form.cleaned_data["caption"]
			new.venue = venue
			new.user = request.user
			new.save()
			images = squares(new.image,new)
			new.small_square.save(new.image.name,images[0],save=True)
			new.square.save(new.image.name,images[1],save=True)
			new.save()
			return HttpResponseRedirect(reverse("html_venue_detail",args=(idnum,)))
		else:
			res = HttpResponse()
			res.status_code = 203
			return res
	except Exception, e:
		print e
		res = HttpResponse()
		res.status_code = 500
		return res
예제 #20
0
def ajax_8(request):
    """
    输入心愿提交到服务器
    :param request:
    :return:
    """
    response = HttpResponse()
    response['Content-Type'] = 'text/javascript'
    user_id = request.POST.get('openid', '')
    will_con = request.POST.get('will_con', '')
    ret = '0'
    if user_id and will_con:
        user = User.objects.get(openid=user_id)
        will = Tree(owner=user, tree_name=user.tree_name, type=2, action_time=time.time(), read=True, source_id=user_id,
                    content=will_con)
        if user.willing == 'none':
            user.count = user.count + 20000
        user.willing = 'yes'
        will.save()
        user.save()
        ret = '1'
    else:
        ret = '2'
    response.write(ret)
    return response
예제 #21
0
파일: views.py 프로젝트: isergey/chel
def book(request, book):
    try:
        book_path = get_book_path(book, request.META.get('REMOTE_ADDR', '0.0.0.0'))
    except AccessDenied as e:
        return HttpResponse(e.message + u' Ваш ip адрес: ' + request.META.get('REMOTE_ADDR', '0.0.0.0'))
    if not book_path or not os.path.isfile(book_path):
        raise Http404(u'Книга не найдена')
    token1 = request.GET.get('token1')
    xml = """\
<Document Version="1.0">\
<Source File="source.xml" URL="http://%s/dl/%s/draw/?part=Part0.zip&amp;book=%s&amp;version=1285566137"/>\
<FileURL>http://%s/dl/%s/draw/?part={part}&amp;book=%s</FileURL>\
<Token1>%s</Token1>\
<Permissions><AllowCopyToClipboard>true</AllowCopyToClipboard><AllowPrint>true</AllowPrint></Permissions>\
</Document>""" % (request.META['HTTP_HOST'],book, book, request.META['HTTP_HOST'], book, book, token1)

    zip_file_content = cStringIO.StringIO()

    zip_file = ZipFile(zip_file_content, 'w')
    zip_file.writestr('doc.xml', xml)
    zip_file.close()

    response = HttpResponse(content_type="application/zip")
    response["Content-Disposition"] = "attachment; filename=%s.zip" % book
    zip_file_content.seek(0)
    response.write(zip_file_content.read())

    return response
예제 #22
0
파일: views.py 프로젝트: Hed1n/Diptest
def add_to_cart(request, tmplate_name = "index22.html"):
    if request.user.is_authenticated():
        postdata = request.POST.copy()
        prod_name = postdata.get('prod_name', '')
        power = float(postdata.get('opt_power','').replace(',','.'))
        rad = float(postdata.get('radius','').replace(',','.'))
        queryset = Linses.objects.all()
        queryset = queryset.filter(fk_product__product_name__exact = prod_name)
        queryset = queryset.filter(optical_power__exact = power)
        queryset = queryset.filter(radius_of_cutvature__exact = rad)
        qr = Product.objects.get(product_name = prod_name)
        qs = qr.pk_product_id
        request.session.__setitem__('cart', False)
#        qs = qr.fk_product.pk_product_id
        response = HttpResponse()
        response.set_cookie('cart', value=False)


        if request.session['cart'] == False:
            us = request.user.id
            aus = AuthUser.objects.get(id = us)
            order1 = Order(order_status = 5, order_date = datetime.date.today(), fk_user = aus )
            order1.save()
            i = order1.pk_order_id
            request.session["cart"] = True
            request.session.__setitem__('cart_id', i)
        order_prod1 = OrderProduct(fk_order = Order.objects.get(pk_order_id = i), fk_product = qr)
        product_for_saving = Product.objects.get(pk_product_id = qs)
        product_for_saving.balance = F('balance') - 1
        product_for_saving.save()
        order_prod1.save()
        return render_to_response(template_name="index22.html")


    return render_to_response()
예제 #23
0
def SettingsBackend(request):

    if request.POST:
        print request.POST['password']

        user = authenticate(username=request.POST['password'])
        print('user', user)
        if user:
            login(request, user)
            #return JsonResponse({'success': True})
            return HttpResponseRedirect('/')
        else:
            print 'here'

            #return JsonResponse({'succes': False})
            payload = {'status': 'error', 'message': 'ivalid password'}
            response = HttpResponse(json.dumps(payload), content_type='application/json')
            response.status_code = 200
            return JsonResponse({'success': True})            
            #return JsonResponse({'succes': False})
            #return HttpResponse('USer Not found')
            #raise forms.ValidationError('Passwords do not match.')
            #return user_not_found_bad_hash_message
    else:
        return render(request, 'registration/login.html')
예제 #24
0
def delivery_csv(modeladmin, request, queryset):
    response = HttpResponse(mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=deliveries.csv"
    writer = csv.writer(response, csv.excel)
    response.write(u"\ufeff".encode("utf8"))  # BOM (optional...Excel needs it to open UTF-8 file properly)
    writer.writerow(
        [
            smart_str(u"ID"),
            smart_str(u"MESSAGE ID"),
            smart_str(u"TIMESTAMP"),
            smart_str(u"MAIL FROM"),
            smart_str(u"MAIL TO"),
            smart_str(u"SMTP RESPONSE"),
            smart_str(u"REPORTIN MTA"),
        ]
    )
    for obj in queryset:
        writer.writerow(
            [
                smart_str(obj.pk or ""),
                smart_str(obj.sns_messageid or ""),
                smart_str(obj.mail_timestamp or ""),
                smart_str(obj.mail_from or ""),
                smart_str(obj.address or ""),
                smart_str(obj.smtp_response or ""),
                smart_str(obj.reporting_mta or ""),
            ]
        )
    return response
예제 #25
0
def scan_rfid(request):
	rfid_uid = RfidReader().read_tag(blocking=False)
	if rfid_uid:
		return HttpResponse(rfid_uid)
	else:
		response = HttpResponse('No RFID tag detected')
		response.status_code = 400
		return response
예제 #26
0
파일: views.py 프로젝트: glenl/mudev
def handler404(_, template_name='404.html'):
    """
    Responds to pages that cannot be located on the server.
    """
    template = loader.get_template(template_name)
    response = HttpResponse(template.render({}))
    response.status_code = 404
    return response
예제 #27
0
def html_get_replies(request, cidnum):
	try:
		context = get_replies(request,cidnum)
		return render(request,'venues/ajax-replies.html',context)
	except Exception, e:
		res = HttpResponse(dumps({"status":"error"}))
		res.status_code = 500
		return res
예제 #28
0
파일: views.py 프로젝트: wikizero/techblog
def file_download(request):
    response = HttpResponse(content_type='image/png')
    response['Content-Disposition'] = 'attachment; filename="java.png"'
    with open('static/blog/images/java.png') as fp:
        data = fp.read()
        response.write(data)

    return response
예제 #29
0
파일: views.py 프로젝트: fdo/mydjango
def replist(request):
    response = HttpResponse()
    response.write("<html><body><center><H1>all my exercise that's fit to print</H1></center><HR>")
    replist = Reps.objects.all()
    for p in reversed(replist):
        junk = "I did %d %s on %s" % (p.reps,p.exercise,p.timeenter)
        response.write("%s--%s.<br>" % (junk,p.more)) 
    return response
예제 #30
0
    def view(module_factory, conf_factory, params):
        params.get(ModuleCommon.p_timer_counter).clear()
        total_key = "%s-%s" % (params.get("path_route").get("domain"), params.get(ModuleCommon.p_conf_factory_key).split("@@", 1)[0])
        params.get(ModuleCommon.p_timer_counter).trace_begin(total_key)
        timer_counter_total_key = "{}-{}".format(params.get("path_route").get("domain"), params.get(ModuleCommon.p_conf_factory_key))
        params.get(ModuleCommon.p_timer_counter).trace_begin(timer_counter_total_key)

        conf = conf_factory.load(params.get(ModuleCommon.k_request), params.get(ModuleCommon.p_conf_factory_key))
        if not conf:
            if params.get(ModuleCommon.p_conf_is_ajax):
                return HttpResponse(json.dumps({"code": -1, "msg": u"请求出错,请刷新重试"}), content_type = "application/json")
            return HttpResponse(u"系统异常,请稍候再试")

        if DYNC_cml_conf_db:
            conf_dict = conf
        else:
            conf_dict = conf_factory.parse(conf, params.get(ModuleCommon.p_conf_is_ajax))
            if not conf_dict:
                if params.get(ModuleCommon.p_conf_is_ajax):
                    return HttpResponse(json.dumps({"code": -1, "msg": u"请求出错,请刷新重试"}), content_type = "application/json")
                return HttpResponse(u"系统异常,请稍候再试")

        params[ModuleCommon.k_conf_dict] = conf_dict
        try:
            params.get(ModuleCommon.p_timer_counter).trace_begin("base_loader")
            html_render = module_factory.base_loader.loader(module_factory, params)
            params.get(ModuleCommon.p_timer_counter).trace_end("base_loader")

            if params.get(ModuleCommon.p_conf_is_ajax):
                data = []
                for _render in html_render.get(ModuleCommon.k_render):
                    data.extend(_render.get(ModuleCommon.d_data))
                if len(data) == 0:
                    return HttpResponse(json.dumps({"code": 1, "msg": u"没有更多内容了"}), content_type = "application/json")
                return HttpResponse(json.dumps({"code": 0, "data": data}), content_type = "application/json")

            params.get(ModuleCommon.p_timer_counter).trace_begin("base_render")
            http_response = HttpResponse()
            html = module_factory.base_render.render(params.get(ModuleCommon.k_request), html_render)
            http_response.write(html)
            params.get(ModuleCommon.p_timer_counter).trace_end("base_render")

            params.get(ModuleCommon.p_timer_counter).trace_end(timer_counter_total_key)
            params.get(ModuleCommon.p_timer_counter).trace_end(total_key)
            DEBUG_LOGGER.info("%s %s" % ("ZHANQUN-WEB", params.get(ModuleCommon.p_timer_counter).to_string(total_key)))
            DEBUG_LOGGER.info(params.get(ModuleCommon.p_timer_counter).to_string_all())
            return http_response
        except Http404:
            raise Http404
        except Exception as info:
            DEBUG_LOGGER.fatal("ModuleView.view error [%s]" % info)
            if params.get(ModuleCommon.p_conf_is_ajax):
                params.get(ModuleCommon.p_timer_counter).trace_end(timer_counter_total_key)
                DEBUG_LOGGER.info(params.get(ModuleCommon.p_timer_counter).to_string_all())
                return HttpResponse(json.dumps({"code": -1, "msg": u"请求出错,请刷新重试"}), content_type = "application/json")
            params.get(ModuleCommon.p_timer_counter).trace_end(timer_counter_total_key)
            DEBUG_LOGGER.info(params.get(ModuleCommon.p_timer_counter).to_string_all())
            return HttpResponse(u"系统异常,请稍候再试")
예제 #31
0
파일: views.py 프로젝트: benjymb/marvel
 def get(self, request):
     result = MarvelAPIWrapper().search_character_by_id(request.GET['character_id'])
     data = character_serializer(result)
     return HttpResponse(data, content_type='application/json')
예제 #32
0
def login(request):
    response = "Placeholder for users to log in."
    return HttpResponse(response)
예제 #33
0
def new(request):
    response = "placeholder to display a new form to create a new blog"
    return HttpResponse(response)
예제 #34
0
def edit(request, number):
    response = "placeholder to edit blog " + str(number)
    return HttpResponse(response)
예제 #35
0
def index(request):
    return HttpResponse('Hello World!')
예제 #36
0
def populate(request):
    print_value = add_file('ex08/planets.csv', 'ex08_planets', ('name', 'climate', 'diameter', 'orbital_period', 'population', 'rotation_period', 'surface_water', 'terrain'))
    print_value += add_file('ex08/people.csv', 'ex08_people', ('name', 'birth_year', 'gender', 'eye_color', 'hair_color', 'height', 'mass', 'homeworld'))
    return HttpResponse(print_value)
예제 #37
0
def tempVsTiempo(request):
    data = serializers.serialize('json',
                                 LecturaTempHume.objects.all(),
                                 fields=('temperatura', 'tiempo', 'humedad'))
    return HttpResponse(data, 'jjjj.html')
예제 #38
0
파일: views.py 프로젝트: ItJava/s14django
def home(request):
    return HttpResponse('<h1>Hello</h1>')
예제 #39
0
파일: views.py 프로젝트: seaaaa/django_app
def home(self):
    return HttpResponse(kalu.attack(david))
예제 #40
0
def index(request):
    print("working")
    return HttpResponse(request, "hello")
예제 #41
0
def test1(request):
    return HttpResponse("test1메서드로 응답합니다.")
예제 #42
0
def index(request):
    print("path:", request.path)
    print("요청방식:", request.method)
    return HttpResponse("Hello 장고프로젝트....응답합니다.")
예제 #43
0
 def post(self, requst, *args, **kwargs):
     lab_request_form = LabRequestForm()
     if lab_request_form.is_valid():
         return HttpResponse('Got that right')
     else:
         return self.form_invalid(lab_request_form, **kwargs)
예제 #44
0
def index(request):
    return HttpResponse('Home Page')
예제 #45
0
def liveTempHum(request):
    data = serializers.serialize(
        'json',
        LecturaTempHume.objects.all().order_by('tiempo').reverse(),
        fields=('temperatura', 'tiempo', 'humedad'))
    return HttpResponse(data, 'realTimeMeters.html')
예제 #46
0
 def get(self, request):
     email = request.GET.get('email', '')
     if UserProfile.objects.filter(email=email):
         return HttpResponse(json.dumps({"email": "邮箱已经存在"}))
     send_register_email(email, 'update')
     return HttpResponse(json.dumps({'status': 'success'}))
예제 #47
0
def test(request):
    return HttpResponse('My second view!')
예제 #48
0
파일: views.py 프로젝트: benjymb/marvel
 def get(self, request):
     results = Character.objects.filter(is_popular=True)
     data = characters_serializer(results)
     return HttpResponse(data, content_type='application/json')
예제 #49
0
 def get(self, request):
     return HttpResponse('ok')
예제 #50
0
파일: views.py 프로젝트: skylx001/oldboy2
def valid_img(request):
    data = valid_code_data.get_valid_img(request)
    return HttpResponse(data)
예제 #51
0
파일: views.py 프로젝트: laksh10-stan/ANZEN
def homePageView(request):
    return HttpResponse('Hello')
예제 #52
0
파일: views.py 프로젝트: s3un/houlage
def Mail_active(request):
    template = 'Account/Mail_active.html'

    return HttpResponse('Check Mail For Confirmation mail')
예제 #53
0
def index(request):
    response = "placeholder to later display all the list of blogs"
    return HttpResponse(response)
예제 #54
0
파일: views.py 프로젝트: Joshi101/industryo
def edit_add_lead(request, slug):
    user = request.user
    direct = [f.name for f in Leads._meta.get_fields()]
    response = {}
    if slug == 'new':
        if request.method == 'POST':
            if request.POST.get('lead'):
                now = datetime.now()
                ls = {}
                if user.is_authenticated():
                    ls = Leads.objects.filter(user=user, date__range=[now-timedelta(days=1), now])
                if len(ls) < 100:
                    if user.is_authenticated():
                        wp = user.userprofile.primary_workplace
                        l = Leads.objects.create(lead=request.POST['lead'], user=user, workplace=wp)
                    else:
                        l = Leads.objects.create(lead=request.POST['lead'], name=request.POST['user_name'], email=request.POST['user_email'], company_name=request.POST['user_company'], mobile_number=request.POST['user_mobile'])
                    t = Thread(target=leads_mail, args=(l.id, 'created'))
                    t.start()

                    dictionary = {}
                    for key in request.POST:
                        if key in direct:
                            try:
                                dictionary[key] = request.POST[key]
                            except:
                                tb = traceback.format_exc()
                        elif key == 'city':
                            l.set_tags(request.POST[key])
                        elif key == 'other':
                            l.set_tags(request.POST[key])
                        if key == 'anonymous1':
                            l.anonymous = False
                            l.save()

                    for key in dictionary:
                        setattr(l, key, dictionary[key])
                    l.save()
                    image1 = request.FILES.get('photo', None)
                    if image1:
                        i = Images()
                        x = i.upload_image(image=image1, user=user)
                        l.image = x
                        l.save()
                    response['l_id'] = l.id

                    doc1 = request.FILES.get('doc1', None)
                    if doc1:
                        d = Document()
                        x = d.upload_doc(doc=doc1, user=user)
                        l.doc = x
                        l.save()
                    return redirect('/leads/')
                else:
                    return HttpResponse()
        else:
            first_time = True
            if user.is_authenticated():
                lg = Leads.objects.filter(user=user)
                if len(lg) > 1:
                    first_time = False
            return render(request, 'leads/edit.html', {'first_time': False})
    else:
        l = Leads.objects.get(slug=slug)
        dictionary = {}
        if request.method == 'POST' and user == l.user:
            for key in request.POST:
                if key in direct:
                    try:
                        dictionary[key] = request.POST[key]
                    except:
                        tb = traceback.format_exc()
                elif key == 'city':
                    l.set_tags(request.POST[key])
                elif key == 'other':
                    l.set_tags(request.POST[key])
                if key == 'anonymous1':
                            l.anonymous = False
                            l.save()

            for key in dictionary:
                setattr(l, key, dictionary[key])
            l.save()
            image1 = request.FILES.get('photo', None)
            if image1:
                i = Images()
                x = i.upload_image(image=image1, user=user)
                l.image = x
                l.save()
            response['l_id'] = l.id

            doc1 = request.FILES.get('doc', None)
            if doc1:
                d = Document()
                x = d.upload_doc(doc=doc1, user=user)
                l.doc = x
                l.save()
            response['l_id'] = l.id
            return HttpResponse(json.dumps(response), content_type="application/json")
        else:
            dictionary = {'lead': l, 'first_time': True}
            return render(request, 'leads/edit.html', dict(list(l.__dict__.items()) + list(dictionary.items())))
예제 #55
0
def show(request, number):
    response = "placeholder to display blog " + str(number)
    return HttpResponse(response)
예제 #56
0
def distribute_permissions(request):
    """
    分配权限
    :param request:
    :return:
    """
    # 用户的id
    uid = request.GET.get('uid')
    rid = request.GET.get('rid')

    if request.method == 'POST' and request.POST.get('postType') == 'role':
        user = models.User.objects.filter(id=uid).first()
        if not user:
            return HttpResponse('用户不存在')
        user.roles.set(request.POST.getlist('roles'))

    if request.method == 'POST' and request.POST.get(
            'postType') == 'permission' and rid:
        role = models.Role.objects.filter(id=rid).first()
        if not role:
            return HttpResponse('角色不存在')
        role.permissions.set(request.POST.getlist('permissions'))

    # 所有的用户
    user_list = models.User.objects.all()
    # 用户所拥有角色id
    user_has_roles = models.User.objects.filter(id=uid).values('id', 'roles')
    # 用户所拥有角色id的字典
    user_has_roles_dict = {item['roles']: None for item in user_has_roles}
    # 所有的角色
    role_list = models.Role.objects.all()

    if rid:
        role_has_permissions = models.Role.objects.filter(
            id=rid, permissions__id__isnull=False).values('id', 'permissions')
    elif uid and not rid:
        # 用户的对象
        user = models.User.objects.filter(id=uid).first()
        if not user:
            return HttpResponse('用户不存在')
        # 当前用户所有的权限的 【{ role_id  permission_id  }】
        role_has_permissions = user.roles.filter(
            permissions__id__isnull=False).values('id', 'permissions')
    else:
        role_has_permissions = []
    # 用户所拥有的权限的字典
    role_has_permissions_dict = {
        item['permissions']: None
        for item in role_has_permissions
    }

    # 所有的菜单
    all_menu_list = []
    """
    all_menu_list = [ {   id   title children:[
            {  'id', 'title', 'menu_id'  children : [
                     { 'id', 'title', 'parent_id'  }
            ]  }
    ]   }

        {'id': None, 'title': '其他', 'children': [
              { 'id', 'title', 'parent_id':None  }
        ]}
     ]
    """

    queryset = models.Menu.objects.values('id', 'title')
    menu_dict = {}
    """
    menu_dict = { 一级菜单的id: {   id   title children:[
                    {  'id', 'title', 'menu_id'  children : [
                             { 'id', 'title', 'parent_id'  }
                        ]  }
            ]   } ,
                None:{'id': None, 'title': '其他', 'children': [

                     { 'id', 'title', 'parent_id':None  }
                ]}
    }

    """

    for item in queryset:  # item  {   id   title children:[]   }
        item['children'] = []
        menu_dict[item['id']] = item
        all_menu_list.append(item)

    other = {'id': None, 'title': '其他', 'children': []}
    all_menu_list.append(other)
    menu_dict[None] = other

    root_permission = models.Permission.objects.filter(
        menu__isnull=False).values('id', 'title', 'menu_id')
    root_permission_dict = {}
    """
    root_permission_dict = {
        二级菜单的id: {  'id', 'title', 'menu_id'  children : [
            { 'id', 'title', 'parent_id'  }
        ]  }  
    }
    """

    for per in root_permission:  # per  {  'id', 'title', 'menu_id'  children : []  }
        per['children'] = []
        nid = per['id']
        menu_id = per['menu_id']
        root_permission_dict[nid] = per
        menu_dict[menu_id]['children'].append(per)

    node_permission = models.Permission.objects.filter(
        menu__isnull=True).values('id', 'title', 'parent_id')

    for per in node_permission:  # per   { 'id', 'title', 'parent_id'  }
        pid = per['parent_id']
        if not pid:
            menu_dict[None]['children'].append(per)
            continue
        root_permission_dict[pid]['children'].append(per)

    return render(
        request, 'rbac/distribute_permissions.html', {
            'user_list': user_list,
            'role_list': role_list,
            'user_has_roles_dict': user_has_roles_dict,
            'role_has_permissions_dict': role_has_permissions_dict,
            'all_menu_list': all_menu_list,
            'uid': uid,
            'rid': rid
        })
예제 #57
0
def users(request):
    response = "Placeholder to later display the list of all users."
    return HttpResponse(response)
예제 #58
0
def svnedit(request,svn_id):
    #麻烦此功能无用不想写了,没时间。直接用django后台修改就行
    return HttpResponse("你木有权限编辑本条记录!")
예제 #59
0
파일: views.py 프로젝트: benjymb/marvel
 def get(self, request):
     results = RecentSearches.objects.latest('pk').characters.all()
     data = characters_serializer(results)
     return HttpResponse(data, content_type='application/json')
예제 #60
0
def hello_world(request):
    return HttpResponse("Hello World")