예제 #1
0
파일: views.py 프로젝트: km4054/eNarocanje
def exportCSV(request):
    customer_ids = Reservation.objects.filter(service_provider=request.user.service_provider).exclude(customer__isnull=True).values_list('customer_id', flat=True).distinct();
    # Find customers who have not reserved anything yet and were added by service provider
    customers_nonr = Customer.objects.filter(service_provider=request.user.service_provider)
    customers = Customer.objects.filter(pk__in=customer_ids)
    # Merge two QuerySets together
    customers = customers | customers_nonr
    qc = request.GET.get('qc', '')
    # Search by name
    if qc:
        customers = customers.filter(full_name__contains=qc)
    customers = customers.order_by('last_name')

    # Construct HTTP response
    response = HttpResponse(content_type="text/csv")
    response['Content-Disposition'] = 'attachment; filename="customers.csv"'
    writer = csv.writer(response, csv.excel)
    response.write(u'\ufeff'.encode('utf8')) # for excel
    writer.writerow([
        smart_str(u"First_Name"),
        smart_str(u"Last_Name"),
        smart_str(u"Phone"),
        smart_str(u"Email"),
    ])
    for customer in customers:
        writer.writerow([
            smart_str(customer.name),
            smart_str(customer.last_name),
            smart_str(customer.phone),
            smart_str(customer.email),
        ])
    return response
예제 #2
0
def export(request):
    '''
         导出巡检报告
    '''
    response = HttpResponse(content_type='text/plain')                                   
    response['Content-Disposition'] = 'attachment; filename=data.txt'
    report_list = Report.objects.all()
    logger.info(u'获得所有报告')
    parser = Parser(logger)
    i = 1
    seperator = '#'
    for report in report_list:
        pass_rate = float(report.pass_num) / float(report.total_num)
        str_pass_rate = str(int(pass_rate * 100)) + '%'
        #获得巡检报告在服务器的目录
        report_dir = settings.MEDIA_ROOT + report.system + os.path.sep + report.province + os.path.sep + report.reporter
        time_str = os.path.dirname(report.report_path)[-17:]
        time_str.replace('\\',os.path.sep)
        report_dir = report_dir + os.path.sep + time_str
        detail_info = parser.parse_outputxml(report_dir + os.path.sep + 'output.xml')
        if detail_info == '':
        #确少详细信息的记录不导出
            continue
        response.write(str(i) + seperator + report.system + seperator \
                       + report.province + seperator + report.city + seperator \
                       + str(report.total_num) + seperator + str(report.pass_num) + seperator \
                       + str_pass_rate + seperator +  report.sub_time.strftime("%Y-%m-%d") \
                       + seperator + report.reporter + seperator + ' ' + seperator + ' ' + detail_info + seperator)
        i += 1
    return response
예제 #3
0
    def _http_auth_helper(self, request):
        # At this point, the user is either not logged in, or must log
        # in using http auth.  If they have a header that indicates a
        # login attempt, then use this to try to login.
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                if auth[0].lower() == 'basic':
                    # Currently, only basic http auth is used.
                    uname, passwd = base64.b64decode(auth[1]).split(':')
                    user = authenticate(username=uname, password=passwd)
                    if user and user.is_staff:
                        request.session['moat_username'] = uname
                        return

        # The username/password combo was incorrect, or not provided.
        # Challenge the user for a username/password.
        resp = HttpResponse()
        resp.status_code = 401
        try:
            # If we have a realm in our settings, use this for the
            # challenge.
            realm = settings.HTTP_AUTH_REALM
        except AttributeError:
            realm = ""

        resp['WWW-Authenticate'] = 'Basic realm="%s"' % realm
        return resp
예제 #4
0
def attach(request, app_name):
    '''View function to attach facebook/twitter account to user.

    If a twitter account is to be attached, the incoming request is simply an
    indicator. This function then call twitter request_token api to ask for a
    temporary twitter token and twitter secret token, save it to database and
    send back to the client.

    Args:
        request: Incoming request.
        app_name: The name of social network to be attached.

    Returns:
        Token string if twitter token is successfully received. Error message
        if network is not supported.
    '''
    response = HttpResponse()
    if app_name == 'facebook':
        success(request, 'facebook account attached')
    elif app_name == 'twitter':
        request_token_url = 'https://api.twitter.com/oauth/request_token'
        oauth = OAuth1(client_key,
                       client_secret=client_secret)
        r = requests.post(url=request_token_url,
                          auth=oauth,
                          data={'oauth_callback': 'http://ec2-54-173-9-169.compute-1.amazonaws.com:9090/twitter'})
        twitter_query = QueryDict(r.content)
        UserProfile.insert_twitter_token(twitter_query, request.user)
        return HttpResponse(twitter_query['oauth_token'])
    else:
        error(request, 'Unsupported social network')
        response.status_code = 400
    response.write(''.join([item.message for item in get_messages(request)]))
    return response
예제 #5
0
def log_in(request):
    '''View function corresponding to url /login.

    The purpose of this function vary with http method. If method is GET it
    behaves as unauthorize redirect destination; If method is POST it accepts
    request's form data, validates it and adds session to authorize the user.

    Args:
        request: Incoming request

    Returns:
        When GET, indicate the page has been redirected here; When POST,
        return either message that user is logged in or error that form invalid
        or user name/password error.
    '''
    response = HttpResponse()
    if request.method == 'GET':
        info(request, 'Indicator')
    else:
        form = UserForm(request.POST)
        if form.is_valid():
            user = authenticate(username=form.cleaned_data['name'],
                                password=form.cleaned_data['passwd'])
            if user != None:
                login(request, user)
                success(request, 'User exists.')
            else:
                error(request, 'User does not exist.')
                response.status_code = 400
        else:
            error(request, 'Invalid input data')
            response.status_code = 400
    response.write(''.join([item.message for item in get_messages(request)]))
    return response
예제 #6
0
def register(request):
    '''View function handling user registration.

    This function parse and validate incoming request's form data and check
    table auth_user for authenticity before storing user record in table or
    output error message.

    Args:
        request: Incoming request.

    Returns:
        Indicator that user is successfully created or error message that either
        form data is invalid or user exists.
    '''
    form = UserForm(request.POST)
    response = HttpResponse()
    if form.is_valid():
        try:
            user = User.objects.create_user(form.cleaned_data['name'],
                                            password=form.cleaned_data['passwd'])
            success(request, 'Successfully create user.')
        except IntegrityError:
            error(request, 'User name exists.')
            response.status_code = 400
    else:
        error(request, 'Invalid input data')
        response.status_code = 400
    response.write(''.join([item.message for item in get_messages(request)]))
    return response
예제 #7
0
 def download_theme(self, request, pk):
     theme = Theme.objects.get(pk=pk)
     s = io.BytesIO()
     with zipfile.ZipFile(s, 'w', compression=zipfile.ZIP_DEFLATED) as z:
         templates = []
         for template in theme.template_set.filter(enabled=True):
             filename = "templates/{path}".format(
                path=template.path,
                pk=template.pk,
                position=template.position,
                enabled=template.enabled)
             if template not in templates:
                 z.writestr(filename, template.source.encode(settings.FILE_CHARSET))
                 templates.append(template)
         static_files = []
         for static_file in theme.staticfile_set.filter(enabled=True):
             filename = "static/{path}".format(
                path=static_file.path,
                pk=static_file.pk,
                enabled=static_file.enabled)
             content = static_file.file.read()
             if static_file not in static_files:
                 z.writestr(filename, content)
                 static_files.append(static_file)
     response = HttpResponse(content_type="application/x-zip-compressed")
     response['Content-Disposition'] = 'attachment; filename=%s_theme.zip' % theme.name.lower()
     response.write(s.getvalue())
     return response
예제 #8
0
def some_view(request,id):
    envio=Envio.objects.get(pk=id)
    if envio.distribuidor_id == None:
        query_cliente="select c.nombre from cliente c join envio_producto ep on ep.cliente_id = c.id_cliente "\
        " join envio e on e.id_envio = ep.envio_id where e.id_envio="+str(id)
        cliente_nombre=execute_query(query_cliente)[0]
    else:
        cliente_nombre=Distribuidor.objects.get(pk=envio.distribuidor_id).nombre

    query_ep="select count(*),p.codigo,ep.lote, p.nombre,p.precio from envio_producto ep"\
    " join producto p on p.id_producto = ep.producto_id where ep.envio_id= "+str(id)+""\
    " group by p.codigo,ep.lote,p.nombre, p.precio"

    envios_productos=execute_all_query(query_ep)
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Nota de Envio Nro. '+str(envio.nro_talonario)+'.pdf"'

    buffer = BytesIO()

    # Create the PDF object, using the BytesIO object as its "file."

    p = canvas.Canvas(buffer,pagesize=A4)

    encabezado(p,envio.nro_talonario)
    cuerpo(p=p,envio=envio,envios_productos=envios_productos,cliente_nombre=cliente_nombre)
    encabezado(canvas=p, nro=envio.nro_talonario, copia=True)
    cuerpo(p=p, envio=envio, envios_productos=envios_productos, copia=True, cliente_nombre=cliente_nombre)
    # Get the value of the BytesIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
예제 #9
0
    def process_request(self, request):
        """
        Parse the session id from the 'Session-Id: ' header when using the api.
        """
        if self.is_api_request(request):
            try:
                parsed_session_uri = parse_session_id(request)
                if parsed_session_uri is not None:
                    domain = get_domain(request)
                    if parsed_session_uri['realm'] != domain:
                        raise exceptions.PermissionDenied(
                            _('Can not accept cookie with realm %s on realm %s') % (
                                parsed_session_uri['realm'],
                                domain
                            )
                        )
                    session_id = session_id_from_parsed_session_uri(
                        parsed_session_uri)
                    request.session = start_or_resume(
                        session_id, session_type=parsed_session_uri['type'])
                    request.parsed_session_uri = parsed_session_uri

                    # since the session id is assigned by the CLIENT, there is
                    # no point in having csrf_protection. Session id's read
                    # from cookies, still need csrf!
                    request.csrf_processing_done = True
                    return None
            except exceptions.APIException as e:
                response = HttpResponse('{"reason": "%s"}' % e.detail,
                                        content_type='application/json')
                response.status_code = e.status_code
                return response

        return super(HeaderSessionMiddleware, self).process_request(request)
예제 #10
0
    def run(self):
        
        if self.input_Request.GET.get("unlogin")!=None:
            return self.unlogin()

        beijing={"id":1,"name":"北京"}
        shanghai={"id":2,"name":"上海"}
        userAreas=[beijing,shanghai]
        dataset={"result":"","areas":userAreas}
        
        if self.input_Request.method=="POST":
            getUserName=self.input_Request.POST.get("txtUserName")
            getUserPass=self.input_Request.POST.get("txtUserPass")
            
            Login_result=self.login(getUserName,getUserPass)
        
            if Login_result:
                myResponse=HttpResponse("<script>self.location='/index/index'</script>")
                myResponse.set_cookie("userlogin_username",getUserName,3600)
                return myResponse
            else:
                dataset["result"]="用户名和密码错误"
            
        myResponse=render_to_response("userlogin.html",dataset)  

        return render_to_response("userlogin.html",dataset)    
예제 #11
0
def response_for_download(report, cd_value='attachment'):
    """
    Preparing response for downloading file
    Content-Disposition header field from http://tools.ietf.org/html/rfc2183
    :param:     report - instance of Report model
    :param:     cd_value - Content Disposition Value:
                    "attachment" - for download
                    "inline" - for preview
    :return:    HttpResponse with report.file and some parameters
    """
    path = report.file.path
    fileExt  = os.path.splitext(report.filename)[1]  # [0] returns path+filename
    ct = get_mimeType().get(fileExt.lower(), "application/octet-stream")
    filename = report.filename
    cdv = '%s; ' % cd_value
    fn = 'filename="%s"; ' % transliterate(filename)
    fns = "filename*=utf-8''%s; " % urlquote(filename)
    md = 'modification-date="%s"; ' % report.uploaded_on
    response = HttpResponse(content_type=ct)
    # content = report.file.read()
    with open(path, 'rb') as file:
        content = file.read()   # читаємо файл незалежно від report
                                # (інакше при тестуванні не завжди
                                # вдається видалити тимчасовий файл)
    response.write(content)
    response['Content-Disposition'] = cdv + fn + fns + md
    response['Content-Length'] = report.file.size
    return response
예제 #12
0
    def process_cache_response(self,
                               view_instance,
                               view_method,
                               request,
                               args,
                               kwargs):
        key = self.calculate_key(
            view_instance=view_instance,
            view_method=view_method,
            request=request,
            args=args,
            kwargs=kwargs
        )
        response = self.cache.get(key)
        if not response:
            response = view_method(view_instance, request, *args, **kwargs)
            response = view_instance.finalize_response(request, response, *args, **kwargs)
            response.render()  # should be rendered, before picklining while storing to cache

            if not response.status_code >= 400 or self.cache_errors:
                response_dict = (
                    response.rendered_content,
                    response.status_code,
                    response._headers
                )
                self.cache.set(key, response_dict, self.timeout)
        else:
            content, status, headers = response
            response = HttpResponse(content=content, status=status)
            response._headers = headers

        if not hasattr(response, '_closable_objects'):
            response._closable_objects = []

        return response
예제 #13
0
def postImageContent(request):
    userId = request.session.get(KEY_USER_ID, '')
    if not userId:
        return HttpResponse('你还未登录或登录已过期')

    print(str(request.POST))

    images = request.POST.getlist('images[]')
    texts = request.POST.getlist('texts[]')
    title = request.POST.get('title')
    category = request.POST.get('category')
    author = request.POST.get('author')

    print("分类:", category)

    articleType = 3  # 图文
    contentType = 3 # 图文


    if articleService.addImageArticle(userId, title, category, contentType, articleType, images, texts, author):
        return HttpResponse(SUCCESS)
    else:
        response = HttpResponse(ERROR)
        response.status_code = 500
        return response
예제 #14
0
	def render_pdf( self, html, filename = None ):
		response = HttpResponse( content_type = self.PDF_CNT_TYPE )

		w = Watch( "BaseView.render_pdf" )
		w.start()

		if filename == None:
			filename = datetime.now().strftime( "%Y%m%d" ) + '-export.pdf'

		pdf_path = settings.MEDIA_ROOT + '/pdf/contracts/' + filename
		pdf_file = open( pdf_path, "w+b" )

		try:
			pisa.CreatePDF( html, dest = pdf_file )
		except Exception as e	:
			print ( traceback.format_exc() )

		pdf_file.seek( 0 )
		pdf = pdf_file.read()
		pdf_file.close()

		response['Content-Disposition'] = filename
		response["Cache-Control"] = "max-age=0"
		response["Accept-Ranges"] = "none"
		response.content = pdf

		print( "Rendering PDF took :" )
		print( w.display() )

		return response
예제 #15
0
def export_csv_photo(modeladmin, request, queryset):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=tigatrapp_photos.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"url"),
        smart_str(u"user"),
        smart_str(u"report"),
        smart_str(u"date"),
        smart_str(u"report_lat"),
        smart_str(u"report_lon"),
        smart_str(u"report_note"),
        smart_str(u"report_type"),
        smart_str(u"report_responses"),
    ])
    for obj in queryset:
        writer.writerow([
            smart_str(obj.id),
            smart_str("http://%s%s" % (request.get_host(), obj.photo.url)),
            smart_str(obj.user),
            smart_str(obj.report),
            smart_str(obj.date),
            smart_str(obj.report.lat),
            smart_str(obj.report.lon),
            smart_str(obj.report.note),
            smart_str(obj.report.type),
            smart_str(obj.report.response_string),

        ])
    return response
예제 #16
0
def generar_pdf(request, message):
    # message = ''
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    buffer = BytesIO()

    # Create the PDF object, using the BytesIO object as its "file."
    p = canvas.Canvas(buffer, pagesize=A4)
    p.setLineWidth(.30)
    p.setFont('Helvetica', 22)
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(30, 750, "Hello world. " + message)
    p.drawImage('static/nao.png',440,720,100,100)

    # Close the PDF object cleanly.
    p.showPage()
    p.save()

    # Get the value of the BytesIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    #startfile(pdf)
    response.write(pdf)

    # context = {'message' : message}
    #render(request , 'prueba.html',context)
    return response
예제 #17
0
    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type="application/svg")
        response['Content-Disposition'] = 'attachment; filename="planner2015.pdf"'

        svg = output_svg_planner(output_format="buffer", file_format="pdf")
        response.write(svg)
        return response
예제 #18
0
    def get(self, request, *args, **kwargs):
        importer = request.GET.get("importer")
        file_name = request.GET.get("file_name")
        if not importer or not file_name:
            return HttpResponseBadRequest(_("Invalid parameters"))

        importer_cls = get_importer(importer)
        if not importer_cls or not importer_cls.has_example_file():
            raise Http404(_("Invalid importer"))

        example_file = importer_cls.get_example_file(file_name)
        if not example_file:
            raise Http404(_("Invalid file name"))

        response = HttpResponse(content_type=example_file.content_type)
        response['Content-Disposition'] = 'attachment; filename=%s' % example_file.file_name

        data = importer_cls.get_example_file_content(example_file, request)

        if not data:
            raise Http404(_("File not found"))

        data.seek(0)
        response.write(data.getvalue())
        return response
예제 #19
0
 def export_response(self):
     response = HttpResponse(content_type=self.export.get_content_type())
     response['Content-Disposition'] = 'attachment; filename="{0}"'.format(
         self.filename
     )
     response.write(self.export_bytes())
     return response
예제 #20
0
파일: views.py 프로젝트: or/jeeves
    def post(self, request, *args, **kwargs):
        payload = json.loads(request.body.decode('utf-8'))

        if request.META.get('HTTP_X_GITHUB_EVENT') == "ping":
            return HttpResponse('Hi!')

        if False:
            if request.META.get('HTTP_X_GITHUB_EVENT') != "push":
                response = HttpResponse()
                response.status_code = 403
                return response

            signature = request.META.get('HTTP_X_HUB_SIGNATURE').split('=')[1]
            secret = settings.GITHUB_HOOK_SECRET
            if isinstance(secret, str):
                secret = secret.encode('utf-8')

            mac = hmac.new(secret, msg=request.body, digestmod=sha1)
            if not hmac.compare_digest(mac.hexdigest(), signature):
                response = HttpResponse()
                response.status_code = 403
                return response

        handle_push_hook_request(payload)

        return HttpResponse("OK")
예제 #21
0
파일: views.py 프로젝트: bellum/test_7web
 def post(self, request, *args, **kwargs):
     """
     Doesn't allow requests from localhost.
     If form data is correct, function adds new Note object.
     If not, returns form with errors.
     Allows CORS.
     """
     response = HttpResponse()
     response['Content-Type'] = 'application/json'
     response['Access-Control-Allow-Origin'] = '*'
     response['Access-Control-Allow-Credentials'] = 'true'
     response['Access-Control-Allow-Methods'] = ', '.join(self.default_methods)
     response['Access-Control-Allow-Headers'] = ', '.join(self.default_headers)
     if request.META['REMOTE_ADDR'] == '127.0.0.1':
         content = {'result': 'error', 'msg': 'POST is not allowed from localhost.'}
     else:
         form = AddNoteForm(request.POST, request.FILES)
         if form.is_valid():
             text = form.cleaned_data['text']
             img = form.cleaned_data['img']
             Note.objects.create(text=text, img=img)
             content = {'result': 'success', 'redirect': reverse('note_list')}
         else:
             t = loader.get_template('add_note_form.html')
             ctx = RequestContext(request, {'form': form})
             form_with_errors = t.render(ctx)
             content = {'result': 'success', 'form': unicode(form_with_errors)}
     response.content = json.dumps(content)
     return response
예제 #22
0
 def render_data_to_response(self, table_data, **kwargs):
     f = StringIO()
     f.write(os.linesep.join([self.delimiter.join(map(str, row)) for row in table_data]))
     response = HttpResponse(content_type="application/octet-stream")
     response["Content-Disposition"] = "attachment; filename=%s" % urlquote(self.full_file_name)
     response.write(f.getvalue())
     return response
예제 #23
0
파일: views.py 프로젝트: or/jeeves
    def get(self, request, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

        build = self.get_object()
        response = HttpResponse(content_type="text/plain")
        response.write(build.get_log())
        return response
예제 #24
0
 def get(self, request, *args, **kwargs):
     super(BulkLicenceRenewalPDFView, self).get(request, *args, **kwargs)
     licences = []
     if self.qs:
         licences = self.qs
     response = HttpResponse(content_type='application/pdf')
     response.write(bulk_licence_renewal_pdf_bytes(licences, request.build_absolute_uri(reverse('home'))))
     return response
예제 #25
0
def index(request):
		response_data = {}
		response_data['server'] = 'oauth2_server.com'
		response_data['version'] = 'django {0}'.format(get_version())

		resp = HttpResponse(json.dumps(response_data), content_type="application/json")
		resp.status_code = 200
		return resp
예제 #26
0
def get_finance_file(request):
    path = request.GET.get('path')
    name = path.split('/')[-1]
    c = open(path, 'rb').read()
    response = HttpResponse()
    response['Content-Disposition'] = 'attachment;filename="%s"' % name
    response.write(c)
    return response
예제 #27
0
파일: views.py 프로젝트: eiscalle/project
def make_response(status=200, content=None):
    if content is None:
        content = {}
    response = HttpResponse()
    response.status_code = status
    response['Content-Type'] = "application/json"
    response.content = json.dumps(content)
    return response
예제 #28
0
def object_to_json_response(obj, status=200):
    """
    Given an object, returns an HttpResponse object with a JSON serialized
    version of that object
    """
    data = json.dumps(obj, ensure_ascii=False)
    response = HttpResponse(content_type='application/json', status=status)
    response.write(data)
    return response
예제 #29
0
def is_logged(request):
    if request.user.is_authenticated():
        res = HttpResponse("")
        res.status_code = 200
        return res
    else:
        res = HttpResponse("Unauthorized")
        res.status_code = 401
        return res
예제 #30
0
def process_output(request, book_id=0):
    response = HttpResponse()
    start_line = int(request.GET.get('start_line', 0))
    log_file = get_log_file(book_id)
    with open(log_file, 'r') as fp:
        for i, line in enumerate(fp):
            if i >= start_line:
                response.write(line)
    return response
예제 #31
0
def sourcecodesubmit(request):
    user = request.user

    if user.groups.filter(name='sourcecode').exists():
        gamestatus = SourcecodeUser.objects.filter(user=user)[0]
        answersAll = Sourcecode.objects.filter(user=user)
        #if gamestatus.gameover == 1:
        #   return HttpResponseRedirect('/Sourcecode/done')
        playstart = SourcecodeUser.objects.filter(user=user)[0]
        bidded = Sourcecode.objects.filter(user=user)[0]

        if len(answersAll) == 0:
            if request.method == "POST":
                v = request.POST.get('number')
                points = request.POST.get('points')
                bidded_points = int(bidded.points)
                newpoints = bidded_points - int(points)
                if 0:
                    return redirect('https://www.codechef.com/')
                else:
                    if v == '1':
                        if playstart.last_played > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now() - playstart.last_played
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid1:
                            return redirect('https://www.codechef.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question1=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid1=1)
                        Sourcecodeanswer.save()
                        return render(
                            request, 'sourcecodestart1.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '2':
                        if playstart.last_played2 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played2
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid2:
                            return redirect('https://www.codechef.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question2=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid2=1)
                        Sourcecodeanswer.save()
                        return render(
                            request, 'sourcecodestart2.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '3':
                        if playstart.last_played3 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played3
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid3:
                            return redirect('https://www.google.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question3=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid3=1)
                        Sourcecodeanswer.save()
                        return render(
                            request, 'sourcecodestart3.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '4':
                        if playstart.last_played4 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played4
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid4:
                            return redirect('https://www.google.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question4=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid4=1)
                        Sourcecodeanswer.save()
                        return render(
                            request, 'sourcecodestart4.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '5':
                        if playstart.last_played5 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played5
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid5:
                            return redirect('https://www.google.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question5=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid5=1)
                        Sourcecodeanswer.save()
                        return render(
                            request, 'sourcecodestart5.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '6':
                        if playstart.last_played6 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played6
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid6:
                            return redirect('https://www.google.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question6=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid6=1)
                        Sourcecodeanswer.save()
                        return render(
                            request, 'sourcecodestart6.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
        else:
            if request.method == "POST":
                v = request.POST.get('number')
                points = request.POST.get('points')
                bidded_points = int(bidded.points)
                newpoints = bidded_points - int(points)
                if 0:
                    return redirect('https://www.codechef.com/')
                else:
                    if v == '1':
                        if playstart.last_played > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now() - playstart.last_played
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid1:
                            return redirect('https://www.codechef.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question1=points)
                        Sourcecode.objects.filter(user=user).update(
                            question1=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid1=1)
                        return render(
                            request, 'sourcecodestart1.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '2':
                        if playstart.last_played2 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played2
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid2:
                            return redirect('https://www.codechef.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question2=points)
                        Sourcecode.objects.filter(user=user).update(
                            question2=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid2=1)
                        return render(
                            request, 'sourcecodestart2.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '3':
                        if playstart.last_played3 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played3
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid3:
                            return redirect('https://www.codechef.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question3=points)
                        Sourcecode.objects.filter(user=user).update(
                            question3=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid3=1)
                        return render(
                            request, 'sourcecodestart3.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '4':
                        if playstart.last_played4 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played4
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid4:
                            return redirect('https://www.google.com/')
                        Sourcecodeanswer = Sourcecode(user=user,
                                                      question4=points)
                        Sourcecode.objects.filter(user=user).update(
                            question4=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid4=1)
                        return render(
                            request, 'sourcecodestart4.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '5':
                        if playstart.last_played5 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played5
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid5:
                            return redirect('https://www.google.com/')
                        Sourcecode.objects.filter(user=user).update(
                            question5=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid5=1)
                        return render(
                            request, 'sourcecodestart5.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
                    elif v == '6':
                        if playstart.last_played6 > timezone.now() - timedelta(
                                minutes=30):
                            timeremain = timezone.now(
                            ) - playstart.last_played6
                            minremain = int((timeremain.seconds) / 60)
                            secremain = int((timeremain.seconds) % 60)
                        else:
                            minremain = 0
                            secremain = 0
                        if bidded.bid6:
                            return redirect('https://www.google.com/')
                        Sourcecode.objects.filter(user=user).update(
                            question6=points)
                        Sourcecode.objects.filter(user=user).update(
                            points=newpoints, bid6=1)
                        return render(
                            request, 'sourcecodestart6.html', {
                                'minremain': minremain,
                                'points': bidded.points,
                                'secremain': secremain,
                                'start': 1
                            })
    else:
        return HttpResponse("Not authorised to view the page")
예제 #32
0
def basic_one(request):
    view = "basic_one"
    html = "<html><body>This is %s view</html></body>" % view
    return HttpResponse(html)
예제 #33
0
def oleg(request):
    return HttpResponse("Hello, Oleg")
예제 #34
0
def export_coupon_excel(request):
    user = request.user
    item_list = UserEvent.objects
    startTime = request.GET.get("startTime", None)
    endTime = request.GET.get("endTime", None)
    startTime2 = request.GET.get("startTime2", None)
    endTime2 = request.GET.get("endTime2", None)
    state = request.GET.get("state", '1')
    projecttype = request.GET.get("projecttype", '0')
    if startTime and endTime:
        s = datetime.datetime.strptime(startTime, '%Y-%m-%dT%H:%M')
        e = datetime.datetime.strptime(endTime, '%Y-%m-%dT%H:%M')
        item_list = item_list.filter(time__range=(s, e))
    if startTime2 and endTime2:
        s = datetime.datetime.strptime(startTime2, '%Y-%m-%dT%H:%M')
        e = datetime.datetime.strptime(endTime2, '%Y-%m-%dT%H:%M')
        item_list = item_list.filter(audit_time__range=(s, e))

    username = request.GET.get("username", None)
    if username:
        item_list = item_list.filter(user__username=username)

    mobile = request.GET.get("mobile", None)
    if mobile:
        item_list = item_list.filter(user__mobile=mobile)

    mobile_sub = request.GET.get("mobile_sub", None)
    if mobile_sub:
        item_list = item_list.filter(invest_account=mobile_sub)

    companyname = request.GET.get("companyname", None)
    if companyname:
        item_list = item_list.filter(
            coupon__project__provider__contains=companyname)

    projectname = request.GET.get("projectname", None)
    if projectname:
        item_list = item_list.filter(
            coupon__project__title__contains=projectname)

    adminname = request.GET.get("adminname", None)
    if adminname:
        item_list = item_list.filter(audited_logs__user__username=adminname)
    if projecttype == '1':
        item_list = item_list.filter(coupon__project__ctype='0')
    if projecttype == '2':
        item_list = item_list.filter(coupon__project__ctype='1')
    item_list = item_list.filter(
        event_type='4',
        audit_state=state).select_related('user').order_by('time')

    data = []
    for con in item_list:
        coupon = con.content_object
        id = str(con.id)
        user_type = u"普通用户" if not con.user.is_channel else u"渠道:" + con.user.channel.level
        user_mobile = con.user.mobile if not con.user.is_channel else con.user.channel.qq_number
        time_sub = con.time.strftime("%Y-%m-%d %H:%M")
        title = coupon.project.title
        zhifubao = con.user.zhifubao
        mobile_sub = con.invest_account
        term = con.invest_term
        invest_amount = con.invest_amount
        remark = con.remark
        result = ''
        return_amount = ''
        reason = ''
        if con.audit_state == '0':
            result = u'是'
            if con.translist.exists():
                return_amount = str(con.translist.first().transAmount / 100.0)
        elif con.audit_state == '2':
            result = u'否'
            if con.audited_logs.exists():
                reason = con.audited_logs.first().reason
        data.append([
            id, user_type, user_mobile, time_sub, title, zhifubao, mobile_sub,
            term, invest_amount, remark, result, return_amount, reason
        ])
    w = Workbook()  #创建一个工作簿
    ws = w.add_sheet(u'待审核记录')  #创建一个工作表
    title_row = [
        u'记录ID', u'用户类型', u'挖福利账号', u'提交时间', u'项目名称', u'支付宝', u'注册手机号',
        u'投资期限', u'投资金额', u'备注', u'审核结果(0通过,1待审核,2拒绝)', u'返现金额', u'拒绝原因'
    ]
    for i in range(len(title_row)):
        ws.write(0, i, title_row[i])
    row = len(data)
    style1 = easyxf(num_format_str='YY/MM/DD')
    for i in range(row):
        lis = data[i]
        col = len(lis)
        for j in range(col):
            if j == 3:
                ws.write(i + 1, j, lis[j], style1)
            else:
                ws.write(i + 1, j, lis[j])
    sio = StringIO.StringIO()
    w.save(sio)
    sio.seek(0)
    response = HttpResponse(sio.getvalue(),
                            content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=优惠券待审核记录.xls'
    response.write(sio.getvalue())

    return response
예제 #35
0
    def get(self, request, *args, **kwargs):

        query = TiempoMuertoEnc.objects.all()
        wb = Workbook()

        ws = wb.active
        ws.tittle = 'Tiempos Muertos'

        #Establer el nombre del archivo
        nombre_archivo = "Reporte Tiempos Muertosw.xlsx"
        ws['B1'].alignment = Alignment(horizontal='left', vertical='center')
        ws['B1'].border = Border(left=Side(border_style='thin'),
                                 right=Side(border_style='thin'),
                                 top=Side(border_style='thin'),
                                 bottom=Side(border_style='thin'))

        ws['B1'].fill = PatternFill(start_color='66FFCC',
                                    end_color='66FFCC',
                                    fill_type='solid')
        ws['B1'].font = Font(name='calibri', size=12, bold=True)
        ws['B1'] = 'Company'

        ws.merge_cells('B1:F1')

        ws['B2'].alignment = Alignment(horizontal='left', vertical='center')
        ws['B2'].border = Border(left=Side(border_style='thin'),
                                 right=Side(border_style='thin'),
                                 top=Side(border_style='thin'),
                                 bottom=Side(border_style='thin'))

        ws['B2'].fill = PatternFill(start_color='66FFCC',
                                    end_color='66FFCC',
                                    fill_type='solid')
        ws['B2'].font = Font(name='calibri', size=12, bold=True)
        ws['B2'] = 'Department'

        ws.merge_cells('B2:F2')
        ws['B3'].alignment = Alignment(horizontal='left', vertical='center')
        ws['B3'].border = Border(left=Side(border_style='thin'),
                                 right=Side(border_style='thin'),
                                 top=Side(border_style='thin'),
                                 bottom=Side(border_style='thin'))

        ws['B3'].fill = PatternFill(start_color='66FFCC',
                                    end_color='66FFCC',
                                    fill_type='solid')
        ws['B3'].font = Font(name='calibri', size=12, bold=True)
        ws['B3'] = 'Reporte de Tiempos Muertos'

        ws.merge_cells('B3:F3')

        ws.row_dimensions[1].height = 20
        ws.row_dimensions[2].height = 20
        ws.row_dimensions[3].height = 20

        ws.column_dimensions['B'].width = 20
        ws.column_dimensions['C'].width = 20
        ws.column_dimensions['D'].width = 20
        ws.column_dimensions['E'].width = 20

        ws['B6'].alignment = Alignment(horizontal='center', vertical='center')
        ws['B6'].border = Border(left=Side(border_style='thin'),
                                 right=Side(border_style='thin'),
                                 top=Side(border_style='thin'),
                                 bottom=Side(border_style='thin'))
        ws['B6'].fill = PatternFill(start_color='66CFCC',
                                    end_color='66CFCC',
                                    fill_type='solid')
        ws['B6'].font = Font(name='calibri', size=11, bold=True)
        ws['B6'] = 'Fecha'

        ws['C6'].alignment = Alignment(horizontal='center', vertical='center')
        ws['C6'].border = Border(left=Side(border_style='thin'),
                                 right=Side(border_style='thin'),
                                 top=Side(border_style='thin'),
                                 bottom=Side(border_style='thin'))
        ws['C6'].fill = PatternFill(start_color='66CFCC',
                                    end_color='66CFCC',
                                    fill_type='solid')
        ws['C6'].font = Font(name='calibri', size=11, bold=True)
        ws['C6'] = 'Planta'

        controlador = 7
        for q in query:
            ws.cell(row=controlador,
                    column=2).alignment = Alignment(horizontal='center',
                                                    vertical='center')
            ws.cell(row=controlador,
                    column=2).border = Border(left=Side(border_style='thin'),
                                              right=Side(border_style='thin'),
                                              top=Side(border_style='thin'),
                                              bottom=Side(border_style='thin'))
            ws.cell(row=controlador,
                    column=2).fill = PatternFill(start_color='66CFCC',
                                                 end_color='66CFCC',
                                                 fill_type='solid')
            ws.cell(row=controlador, column=2).font = Font(name='calibri',
                                                           size=11,
                                                           bold=True)
            ws.cell(row=controlador, column=2).value = q.fecha_produccion

            ws.cell(row=controlador,
                    column=3).alignment = Alignment(horizontal='center',
                                                    vertical='center')
            ws.cell(row=controlador,
                    column=3).border = Border(left=Side(border_style='thin'),
                                              right=Side(border_style='thin'),
                                              top=Side(border_style='thin'),
                                              bottom=Side(border_style='thin'))
            ws.cell(row=controlador,
                    column=3).fill = PatternFill(start_color='66CFCC',
                                                 end_color='66CFCC',
                                                 fill_type='solid')
            ws.cell(row=controlador, column=3).font = Font(name='calibri',
                                                           size=11,
                                                           bold=True)
            ws.cell(row=controlador, column=3).value = str(q.linea)

            for det in q.tiempo_muerto:

                ws.cell(row=controlador,
                        column=4).alignment = Alignment(horizontal='center',
                                                        vertical='center')
                ws.cell(row=controlador, column=4).border = Border(
                    left=Side(border_style='thin'),
                    right=Side(border_style='thin'),
                    top=Side(border_style='thin'),
                    bottom=Side(border_style='thin'))
                ws.cell(row=controlador,
                        column=4).fill = PatternFill(start_color='66CFCC',
                                                     end_color='66CFCC',
                                                     fill_type='solid')
                ws.cell(row=controlador, column=4).font = Font(name='calibri',
                                                               size=11,
                                                               bold=True)
                ws.cell(row=controlador, column=4).value = str(det)

            #contador+=1
            controlador += 1

        response = HttpResponse(content_type='application/ms-excel')
        contenido = "attachment; filename = {0}".format(nombre_archivo)
        response["Content-Disposition"] = contenido
        wb.save(response)
        return response
예제 #36
0
def status(request):
    return HttpResponse("ok")
예제 #37
0
 def process(self, request, ids):
     request.session["mass_action_ids"] = ids
     return HttpResponse("ok")
예제 #38
0
def can_view_courses_list(request):
    if not request.user.is_staff:
        return None, HttpResponse('Unauthorized', status=401)
    else:
        courses = Course.objects.filter(is_draft=False,is_archived=False).order_by('title')
    return courses, None
예제 #39
0
파일: views.py 프로젝트: ludechu/DJevn
def setcookie(request):
    """设置cookie"""
    res = HttpResponse()
    res.set_cookie("ldc","123456")
    return HttpResponse("Cookie设置成功")
예제 #40
0
파일: views.py 프로젝트: ludechu/DJevn
def post1(request):
    """post获取浏览器提交数据实例"""
    name = request.POST['name']
    hobby = request.POST.getlist('hobby')
    return HttpResponse(name+hobby[0])
예제 #41
0
파일: views.py 프로젝트: ludechu/DJevn
def login1(request):
    res = HttpResponse()
    cookie = res.set_cookie("ldc","123456")
    # cookie1 = res.delete_cookie("ldc")
    return HttpResponse("aaa")
예제 #42
0
파일: views.py 프로젝트: ludechu/DJevn
def get1(request):
    """get获取浏览器传递的参数"""
    a = request.GET.get('a')
    b = request.GET['b']
    c = request.GET.get('c')
    return HttpResponse("get1页面"+"参数a:"+a+"参数b"+b+"参数c"+c)
예제 #43
0
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http.response import HttpResponse
from django.views.static import serve as static_serve
# from wiki.compat import include, url
from django_nyt.urls import get_pattern as get_notify_pattern
from wiki.urls import get_pattern as get_wiki_pattern
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic.base import RedirectView

admin.autodiscover()

urlpatterns = [
    url(r'^admin/clearcache/', include('clearcache.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^robots.txt', lambda _: HttpResponse('User-agent: *\nDisallow: /')),
    # url(r'^silk/', include('silk.urls', namespace='silk')),
    url(r'^favicon\.ico$', RedirectView.as_view(url='/media/wiki/images/favicon.ico')), # need this to tell Chrome where to find the favicon. Note that png doesnt work.
]



urlpatterns += [
    url(r'^notify/', include('django_nyt.urls')),
    url(r'', include('wiki.urls')),
]

handler500 = 'xp.views.server_error'
handler404 = 'xp.views.page_not_found'

예제 #44
0
 def get(self, request, *args, **kwargs):
     if self.request.GET.get(u'hub.verify_token') == SECRET_KEY:
         return HttpResponse(self.request.GET['hub.challenge'])
     else:
         return HttpResponse('Error, invalid token')
예제 #45
0
def revenue(request):
    user = request.user
    frui = fruits.objects.filter(farmer_id=user.id)
    print(frui)
    return HttpResponse('<h1>Revenue</h1>')
예제 #46
0
def approve_course_preference(request):
    """
    Bu view katilimci bir kursa kabul edilip edilmedigini görüntülemesi ve katilimcidan katılıp katılmayacağına dair
    son bir teyit alınır.
    :param request: HttpRequest
    :return:
    """
    message = ""
    status = "1"
    data = {"note": "Başvuru Durumunuz"}
    now = datetime.now()
    try:

        data["approve_is_open"] = False
        trainess_course_records = TrainessCourseRecord.objects.filter(trainess=request.user.userprofile,
                                                                      course__site=request.site)
        first_start_date_inst, last_end_date_inst = get_approve_first_start_last_end_dates_for_inst(request.site,
                                                                                                    request.log_extra)
        if not trainess_course_records:
            data['note'] = "Henüz herhangi bir kursa başvuru yapmadınız!"
        elif request.site.application_start_date <= datetime.date(now) < request.site.application_end_date:
            data['note'] = "Başvurunuz için teşekkürler. Değerlendirme sürecinin başlaması için " \
                           "tüm başvuruların tamamlanması beklenmektedir."
        else:
            recordapprovedbyinst = TrainessCourseRecord.objects.filter(trainess=request.user.userprofile, approved=True,
                                                                       consentemailsent=True,
                                                                       course__site=request.site)
            if not recordapprovedbyinst:

                if first_start_date_inst.start_date <= now < last_end_date_inst.end_date:
                    data['note'] = "Başvurular değerlendirilmektedir. En geç %s tarihine kadar sonuçları burada" \
                                   " görebilirsiniz." % last_end_date_inst.end_date.strftime("%d-%m-%Y")
                elif request.site.event_start_date - 1 > now > last_end_date_inst.end_date:
                    data['note'] = "Kurslara kabul dönemi bitmiş olup başvurularınıza kabul edilmediniz ancak" \
                                   " kurs başlangıç tarihine kadar kabul edilme şansınız hala devam ediyor." \
                                   " Takip etmeye devam edin."
                elif request.site.event_start_date - 1 <= now:
                    data['note'] = "Başvurularınız kabul edilmemiştir. Bir sonraki etkinlikte görüşmek dileğiyle."
            else:
                data["note"] = "Aşağıdaki Kursa Kabul Edildiniz"
                data['trainess_course_record'] = recordapprovedbyinst[0]
                if REQUIRE_TRAINESS_APPROVE:
                    recordapprovedbytra = recordapprovedbyinst.filter(trainess_approved=True)
                    if not recordapprovedbytra:
                        tra_approvaldate = ApprovalDate.objects.get(site=request.site, for_trainess=True,
                                                                    preference_order=recordapprovedbyinst[
                                                                        0].preference_order)
                        if tra_approvaldate.start_date <= now <= tra_approvaldate.end_date:
                            data['note'] = "Aşağıdaki kursa kabul edildiniz"
                            data["approve_is_open"] = True
                        else:
                            data[
                                "note"] = "Aşağıdaki kursa kabul edildiniz ancak teyit etmediniz. Kursa katılamazsınız."
                            data["approve_is_open"] = False
    except Exception as e:
        log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=request.log_extra)
        log.error(e.message, extra=request.log_extra)
        data['note'] = "Hata oluştu"
    if request.POST:
        try:
            log.debug(request.POST.get("courseRecordId"), extra=request.log_extra)
            if request.POST.get("courseRecordId") and data['trainess_course_record']:
                data['trainess_course_record'].trainess_approved = True
                data['trainess_course_record'].save()
                message = "İşleminiz başarılı bir şekilde gerçekleştirildi"
                status = "0"
                log.debug("kursu onayladi " + data['trainess_course_record'].course.name, extra=request.log_extra)
        except Exception as e:
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=request.log_extra)
            log.error(e.message, extra=request.log_extra)
            message = "İşleminiz Sırasında Hata Oluştu"
            status = "-1"
        return HttpResponse(json.dumps({'status': status, 'message': message}), content_type="application/json")
    return render(request, "training/confirm_course_preference.html", data)
예제 #47
0
                    # TODO: is this of any use? (yaml inside xml!)
                    if (case.start_log_line is not None
                            and case.end_log_line is not None):
                        logs = read_logs(
                            self.get_object().output_dir,
                            case.start_log_line,
                            case.end_log_line,
                        )
                    tc.add_error_info("failed", output=logs)
                elif case.result == TestCase.RESULT_SKIP:
                    tc.add_skipped_info("skipped")
                cases.append(tc)
            suites.append(junit_xml.TestSuite(suite.name, test_cases=cases))

        data = junit_xml.TestSuite.to_xml_string(suites, encoding="utf-8")
        response = HttpResponse(data, content_type="application/xml")
        response["Content-Disposition"] = ("attachment; filename=job_%d.xml" %
                                           self.get_object().id)
        return response

    @detail_route(methods=["get"], suffix="logs")
    def logs(self, request, **kwargs):
        start = safe_str2int(request.query_params.get("start", 0))
        end = safe_str2int(request.query_params.get("end", None))
        try:
            data = read_logs(self.get_object().output_dir, start, end)
            if not data:
                raise NotFound()
            response = HttpResponse(data, content_type="application/yaml")
            response["Content-Disposition"] = (
                "attachment; filename=job_%d.yaml" % self.get_object().id)
예제 #48
0
    def post(self, request, *args, **kwargs):
        # Converts the text payload into a python dictionary
        incoming_message = json.loads(self.request.body.decode('utf-8'))

        # Facebook recommends going through every entry since they might send
        # multiple messages in a single call during high load

        for entry in incoming_message['entry']:
            for message in entry['messaging']:
                # Check to make sure the received call is a message call
                # This might be delivery, optin, postback for other events
                if 'message' in message:
                    # Print the message to the terminal
                    recieved_messsage = message['message']['text']
                    print(recieved_messsage)

                    # ==================================
                    # integrate Wit.ai bot here
                    # ==================================
                    wit_response = client.message(recieved_messsage)
                    pprint(wit_response)

                    characteristics = get_xter(wit_response)

                    #GEt user details
                    fbid = message['sender']['id']
                    user_details_url = "https://graph.facebook.com/v2.6/{}".format(
                        fbid)
                    user_details_params = {
                        'fields': 'first_name,last_name,profile_pic',
                        'access_token': '{}'.format(PAGE_ACCESS_TOKEN)
                    }
                    user_details = requests.get(user_details_url,
                                                user_details_params).json()

                    message_to_be_sent = generate_response(
                        characteristics, user_details)

                    print(message_to_be_sent)

                    #print user details
                    pprint(user_details)

                    #Do model actions
                    do_actions(characteristics, user_details, fbid)

                    #Send Message
                    post_facebook_message(fbid, message_to_be_sent)

        return HttpResponse()


# def debugview(request):
#     present_date_time=datetime.now()
#     present_date_time_hours=present_date_time-timedelta(
#         minutes=present_date_time.minute,
#         seconds=present_date_time.second,
#         microseconds=present_date_time.microsecond)
#     all_users=our_user.objects.all()
#     for user in all_users:
#         notify_times=user.get_notify_times()
#         print(present_date_time_hours)
#         print(notify_times)

#         if present_date_time_hours in notify_times:
#             print('Yass!! go ahead and send notificatons')

#         else:
#             print('no date_time matches')

#     return HttpResponse('Hello')
예제 #49
0
def ueditor_uploadfile(request):
    """ 上传文件 """
    fileObj = request.FILES.get('upfile', None)
    response = upload_file(fileObj, 'file')
    return HttpResponse(response)
예제 #50
0
 def get(self, request, *args, **kwargs):
     if self.request.GET['hub.verify_token'] == '123456789':
         return HttpResponse(self.request.GET['hub.challenge'])
     else:
         return HttpResponse('Error, invalid token')
예제 #51
0
def report(request):
    return HttpResponse('test')
예제 #52
0
def result(request):
    """ Обработчик результата оплаты """
    data = request.POST
    urlencoded = data.urlencode().replace('&', '\n')

    # log data
    Log.objects.create(
        inv_id=data.get('x_invoice_num'),
        status=Log.STATUS_MESSAGE,
        request=urlencoded,
    )

    form = AuthorizeNetResultForm(data)
    if form.is_valid():
        invoice = form.cleaned_data['x_invoice_num']
        try:
            invoice = int(invoice)
        except (TypeError, ValueError):
            invoice = None

        response_code = form.cleaned_data['x_response_code']
        if response_code == AuthorizeNetResultForm.RESPONSE_CODE_APPROVED:
            # ------------------------------
            #   Approved
            # ------------------------------
            try:
                authorizenet_success.send(
                    sender=Log,
                    invoice=invoice,
                    request=request,
                )
            except Exception as e:
                # log exception
                Log.objects.create(inv_id=invoice,
                                   status=Log.STATUS_EXCEPTION,
                                   request=urlencoded,
                                   message='Signal exception:\n{}: {}'.format(
                                       e.__class__.__name__,
                                       ', '.join(e.args),
                                   ))
            else:
                # log success
                Log.objects.create(
                    inv_id=invoice,
                    status=Log.STATUS_SUCCESS,
                    request=urlencoded,
                )
        else:
            # ------------------------------
            #   Declined или Error
            # ------------------------------
            reason = form.cleaned_data['x_response_reason_text']
            try:
                authorizenet_error.send(
                    sender=Log,
                    invoice=invoice,
                    request=request,
                    code=response_code,
                    reason=reason,
                    subreason=form.cleaned_data.get('EXact_Message'),
                )
            except Exception as e:
                # log exception
                Log.objects.create(inv_id=invoice,
                                   status=Log.STATUS_EXCEPTION,
                                   request=urlencoded,
                                   message='Signal exception:\n{}: {}'.format(
                                       e.__class__.__name__,
                                       ', '.join(e.args),
                                   ))
            else:
                # log fail
                Log.objects.create(
                    inv_id=invoice,
                    status=Log.STATUS_ERROR,
                    request=urlencoded,
                    message=reason,
                )

            return HttpResponse()
    else:
        # log form error
        Log.objects.create(inv_id=data.get('x_invoice_num'),
                           status=Log.STATUS_ERROR,
                           request=urlencoded,
                           message='Invalid form:\n{}'.format(
                               _log_errors(form.errors), ))

    return HttpResponse()
예제 #53
0
def template_two(request):
    view = "template_two"
    t = get_template('myview.html')
    html = t.render({'name': view})
    return HttpResponse(html)
예제 #54
0
파일: views.py 프로젝트: davidcheon/bbs
def bbs_remove(request,bbs_id):
    if request.method=='GET':
        models.BBS.objects.filter(id=bbs_id).delete()
        return HttpResponse('success')
    return HttpResponse('error')
예제 #55
0
def clients_report(request):
    # OPEN WORKBOOK AND HEADER DETAILS
    wb = Workbook()
    ws = wb.active
    ws['A1'] = f'REPORTE DE CLIENTES - {format_date()}'
    ws.merge_cells('A1:C1')

    # HEADERS
    ws['A2'] = 'ID CLIENTE'
    ws['B2'] = 'CORPORACIÓN'
    ws['C2'] = 'RAZÓN SOCIAL'
    ws['D2'] = 'RFC'
    ws['E2'] = 'ID AGENTE VENTA'
    ws['F2'] = 'FECHA ALTA'
    ws['G2'] = 'ESTATUS'
    ws['H2'] = 'BASE DE DATOS'

    # FILTERS
    FullRange = "A2:" + get_column_letter(ws.max_column) + str(ws.max_row)
    ws.auto_filter.ref = FullRange

    # ALIGNMENTS, COLORS AND DIMENSIONS
    dimensions = [13.71, 23.86, 65, 16.43, 23, 15.43, 11.29, 34]

    ws.row_dimensions[1].height = 26.25
    ws.row_dimensions[2].height = 42.75

    ws['A1'].alignment = Alignment(horizontal="center", vertical="center")
    ws['A1'].font = Font(size="20", color="FF0000")

    for col in range(8):
        ws.cell(row=2,
                column=col + 1).alignment = Alignment(horizontal="center",
                                                      vertical="center")
        ws.cell(row=2, column=col + 1).fill = PatternFill(start_color="2F75B5",
                                                          end_color="2F75B5",
                                                          fill_type="solid")
        ws.cell(row=2, column=col + 1).font = Font(size="16", color="FFFFFF")
        ws.cell(row=2, column=col + 1).border = thin_border

    # Column size
    for i, column_width in enumerate(dimensions):
        ws.column_dimensions[get_column_letter(i + 1)].width = column_width + 1

    global query_cache
    counter = 3

    # CREATE EXCEL
    if len(query_cache) > 0:
        print("\nCREATING EXCEL\n")
        for enterprise in query_cache:
            for data in enterprise:
                # ID Cliente
                ws.cell(row=counter, column=1).value = data[2]
                ws.cell(row=counter, column=1).font = Font(size="12")
                ws.cell(row=counter, column=1).border = thin_border
                # Corporación
                ws.cell(row=counter, column=2).value = data[1]
                ws.cell(row=counter, column=2).font = Font(size="12")
                ws.cell(row=counter, column=2).border = thin_border
                # Razón Social
                ws.cell(row=counter, column=3).value = data[3]
                ws.cell(row=counter, column=3).font = Font(size="12")
                ws.cell(row=counter, column=3).border = thin_border
                # RFC
                ws.cell(row=counter, column=4).value = data[4]
                ws.cell(row=counter, column=4).font = Font(size="12")
                ws.cell(row=counter, column=4).border = thin_border
                # ID Agente Venta
                ws.cell(row=counter, column=5).value = data[7]
                ws.cell(row=counter, column=5).font = Font(size="12")
                ws.cell(row=counter, column=5).border = thin_border
                # Fecha Alta
                ws.cell(row=counter,
                        column=6).value = str(data[5]).split(' ')[0]
                ws.cell(row=counter, column=6).font = Font(size="12")
                ws.cell(row=counter, column=6).border = thin_border
                # Estatus
                ws.cell(row=counter, column=7).value = data[6]
                ws.cell(row=counter, column=7).font = Font(size="12")
                ws.cell(row=counter, column=7).border = thin_border
                # Base de datos
                ws.cell(row=counter, column=8).value = data[0]
                ws.cell(row=counter, column=8).font = Font(size="12")
                ws.cell(row=counter, column=8).border = thin_border

                counter += 1
    else:
        print("\nCACHE EMPTY\n")

    # FILE DETAILS AND FORMAT
    filename = 'Reporte_Clientes.xlsx'
    response = HttpResponse(content_type='application/ms-excel')
    content = 'attachment; filename = {0}'.format(filename)
    response['Content-Disposition'] = content
    wb.save(response)

    return response
예제 #56
0
파일: views.py 프로젝트: davidcheon/bbs
def getchatcontent(request,args=None):
    return HttpResponse(chatcontent(request))
예제 #57
0
def sourcecodestart6(request):
    user = request.user

    if user.groups.filter(name='sourcecode').exists():
        answersAll = Sourcecode.objects.filter(user=user)

        bid = Sourcecode.objects.filter(user=user)[0]
        gamestatus = SourcecodeUser.objects.filter(user=user)[0]
        if bid.clickquestion6 == 0:

            firstclick = datetime.now()
            minremain = 00
            secremain = 00
            Sourcecode.objects.filter(user=user).update(clickquestion6=1)
            SourcecodeUser.objects.filter(user=user).update(
                last_played6=firstclick)
        #if len(answersAll)>0:
        #return HttpResponseRedirect('/sourcecode/start1')
        if gamestatus.gameover6 == 1:
            return HttpResponseRedirect('/sourcecode/done')
        if len(SourcecodeUser.objects.filter(user=user)) > 0:
            playstart = SourcecodeUser.objects.filter(user=user)[0]
            if playstart.last_played6 > timezone.now() - timedelta(minutes=30):
                timeremain = timezone.now() - playstart.last_played6
                minremain = int((timeremain.seconds) / 60)
                secremain = int((timeremain.seconds) % 60)
                if (bid.bid6 == 1):
                    return render(
                        request, 'sourcecodestart6.html', {
                            'minremain': minremain,
                            'points': bid.points,
                            'secremain': secremain,
                            'start': 1
                        })
                else:
                    return render(
                        request, 'sourcecodestart6.html', {
                            'minremain': minremain,
                            'points': bid.points,
                            'secremain': secremain,
                            'start': 0
                        })
            else:
                playstart.gameover6 = 1
                playstart.save()
                return HttpResponseRedirect('/sourcecode/success')
        gamestatus.gameover6 = 1
        gamestatus.save()
        if (bid.bid6 == 1):
            return render(
                request, 'sourcecodestart6.html', {
                    'minremain': minremain,
                    'points': bid.points,
                    'secremain': secremain,
                    'start': 1
                })
        else:
            return render(
                request, 'sourcecodestart6.html', {
                    'minremain': minremain,
                    'points': bid.points,
                    'secremain': secremain,
                    'start': 0
                })
    else:
        return HttpResponse("Not authorised to view the page")
예제 #58
0
파일: views.py 프로젝트: davidcheon/bbs
def getonlineusers(request,args=None):
    return  HttpResponse(getonlineuser(request))
예제 #59
0
파일: views.py 프로젝트: ludechu/DJevn
def  index(request):
    list = t_api.apiQuery1.all()
    return HttpResponse("这是首页!%s"%list[0])
예제 #60
0
def response_authenticate():
    """Return 401 response with authenticate header."""
    response = HttpResponse(status=401)
    response['WWW-Authenticate'] = 'Basic realm="Weblate Git access"'
    return response