def view(request): available_projects = request.registry.settings['projects'] selected_project = get_selected_project(request) error_id = request.matchdict['id'] try: error = Error.objects().with_id(error_id) except: return HTTPNotFound() if request.user not in error.seenby: error.seenby.append(request.user) error.save() instances = ErrorInstance.objects(hash=error.hash)[:10] params = { 'error': error, 'selected_project': selected_project, 'available_projects': available_projects, 'instances': instances } try: template = 'error-view/' + str(error['language']).lower() + '.html' return render_to_response(template, params) except: template = 'error-view/generic.html' return render_to_response(template, params)
def home(request): if request.authenticated_userid: user_list = global_db_session.query(User).all() dct = {'user_list': user_list} return render_to_response('templates/users.mako', dct, request=request) else: return render_to_response('templates/index.mako', {}, request=request)
def sample16(request): clientId = request.POST.get('clientId') privateKey = request.POST.get('privateKey') inputFile = request.POST.get('file') url = request.POST.get('url') basePath = request.POST.get('basePath') fileId = request.POST.get('fileId') guid = None iframe = None # Checking required parameters if not clientId or not privateKey: return render_to_response('__main__:templates/sample16.pt', dict(error='You do not enter all parameters')) ### Create Signer, ApiClient and Annotation Api objects # Create signer object signer = GroupDocsRequestSigner(privateKey) # Create apiClient object apiClient = ApiClient(signer) # Create Storage object api = StorageApi(apiClient) if not basePath: basePath = 'https://api.groupdocs.com/v2.0' #Set base path api.basePath = basePath if url: try: # Upload file to current user storage using entered URl to the file upload = api.UploadWeb(clientId, url) guid = upload.result.guid fileId = None except Exception, e: return render_to_response('__main__:templates/sample16.pt', dict(error=str(e)))
def by_activities_public(request): """ Read many Stakeholders based on Activities filter params and/or an Activity ID. Do not return any pending versions. Default output format: JSON """ try: output_format = request.matchdict['output'] except KeyError: output_format = 'json' uids = [] uidsMatchdict = request.matchdict.get('uids', None) if uidsMatchdict is not None: uids = uidsMatchdict.split(',') # Remove any invalid UIDs for uid in uids: if check_valid_uuid(uid) is not True: uids.remove(uid) if output_format == 'json': stakeholders = stakeholder_protocol3.read_many_by_activities(request, uids=uids, public=True) return render_to_response('json', stakeholders, request) elif output_format == 'html': #@TODO return render_to_response('json', {'HTML': 'Coming soon'}, request) else: # If the output format was not found, raise 404 error raise HTTPNotFound()
def read_one_public(request): """ Read one Stakeholder based on ID and return all versions of this Stakeholder. Do not return any pending versions. Default output format: JSON """ try: output_format = request.matchdict['output'] except KeyError: output_format = 'json' uid = request.matchdict.get('uid', None) if check_valid_uuid(uid) is not True: raise HTTPNotFound() if output_format == 'json': stakeholders = stakeholder_protocol3.read_one(request, uid=uid, public=True) return render_to_response('json', stakeholders, request) elif output_format == 'html': #@TODO return render_to_response('json', {'HTML': 'Coming soon'}, request) else: # If the output format was not found, raise 404 error raise HTTPNotFound()
def sample5(request): clientId = os.environ['GROUPDOCS_CID'] privateKey = os.environ['GROUPDOCS_PKEY'] #serviceUrl = os.environ['GROUPDOCS_URL'] srcPath = request.POST.get('srcPath') dstPath = request.POST.get('dstPath') action = request.POST.get('action') if IsNotNull(action) == False or IsNotNull(srcPath) == False or IsNotNull(dstPath) == False: return render_to_response('__main__:templates/sample5.pt', { }) signer = GroupDocsRequestSigner(privateKey) apiClient = ApiClient(signer) api = StorageApi(apiClient) try: docApi = DocApi(apiClient) srcFile = docApi.GetDocumentMetadataByPath(clientId, srcPath) fileID = int(srcFile.result.last_view.document.id) if action == 'copy': newfile = api.MoveFile(clientId, dstPath, Groupdocs_Copy = fileID) if action == 'move': newfile = api.MoveFile(clientId, dstPath, Groupdocs_Move = fileID) except Exception, e: return render_to_response('__main__:templates/sample5.pt', { 'errmsg' : str(e) })
def sample15(request): clientId = request.POST.get("client_id") privateKey = request.POST.get("private_key") # Checking required parameters if IsNotNull(clientId) == False or IsNotNull(privateKey) == False: return render_to_response("__main__:templates/sample15.pt", {"error": "You do not enter all parameters"}) ### Create Signer, ApiClient, StorageApi and Document Api objects # Create signer object signer = GroupDocsRequestSigner(privateKey) # Create apiClient object apiClient = ApiClient(signer) # Create DocApi object doc = DocApi(apiClient) # set total views views = 0 try: # Make a request to Document API response = doc.GetDocumentViews(clientId) if response.status == "Ok": views = len(response.result.views) except Exception, e: return render_to_response("__main__:templates/sample15.pt", {"error": str(e)})
def forbidden(request): if request.user is not None: resp = render_to_response("errors/forbidden.mako", {}, request=request) resp.status = "403 Forbidden" return resp else: return render_to_response("layout2/home_guest.mako", { "forbidden": True }, request=request)
def test_registerTemplateRenderer_explicitrenderer(self): from pyramid import testing def renderer(kw, system): self.assertEqual(kw, {'foo':1, 'bar':2}) renderer = testing.registerTemplateRenderer('templates/foo', renderer) from pyramid.renderers import render_to_response render_to_response('templates/foo', dict(foo=1, bar=2))
def list(request): """brands list """ search = request.params.get("search", "") sort = "name" if request.GET.get("sort") and request.GET.get("sort") == "name": sort = request.GET.get("sort") direction = "asc" if request.GET.get("direction") and request.GET.get("direction") in ["asc", "desc"]: direction = request.GET.get("direction") # db query dbsession = DBSession() query = dbsession.query(Brand).filter(Brand.name.like(search + "%")).order_by(sort + " " + direction) # paginate page_url = paginate.PageURL_WebOb(request) brands = Page(query, page=int(request.params.get("page", 1)), items_per_page=10, url=page_url) if "partial" in request.params: # Render the partial list page return render_to_response("brand/listPartial.html", {"brands": brands}, request=request) else: # Render the full list page return render_to_response("brand/list.html", {"brands": brands}, request=request)
def sample13(request): clientId = request.POST.get('client_id') privateKey = request.POST.get('private_key') fileGuId = request.POST.get('fileId') email = request.POST.get('email') # Checking required parameters if IsNotNull(clientId) == False or IsNotNull(privateKey) == False or IsNotNull(fileGuId) == False or IsNotNull(email) == False: return render_to_response('__main__:templates/sample13.pt', { 'error' : 'You do not enter all parameters' }) ### Create Signer, ApiClient and Annotation Api objects # Create signer object signer = GroupDocsRequestSigner(privateKey) # Create apiClient object apiClient = ApiClient(signer) # Create Annotation object ant = AntApi(apiClient) try: # Make a request to Annotation API ant.SetAnnotationCollaborators(clientId, fileGuId, "v2.0", body=[email]) except Exception, e: return render_to_response('__main__:templates/sample13.pt', { 'error' : str(e) })
def error_view(exc, request, default_message, status=None, outstanding_principals=None, renderer='error.mako'): # Preserve a previously set status code unless specifically overridden if request.response.status != '200 OK': status = status or request.response.status else: status = status or getattr(exc, 'status', None) or 500 request.response.status = status if len(exc.args) and exc.args[0]: message = exc.args[0] else: message = default_message data = { 'http_status': status, 'message': message, 'outstanding_principals': outstanding_principals, } if not renderer: return data elif request.is_xhr: return render_to_response('json', data, request) return render_to_response(renderer, data, request)
def render_page(self, section, redirpath, values=None): if self.endpath is None: return HTTPFound( location=route_url( 'subsections', self.request, action=section, endpath='/'.join(redirpath) )) self.c.active_footer_nav = '-'.join( [self.request.matchdict.get('action')] +list(self.endpath)) for ext in ('.mako', '.rst'): tmpl_path = ('templates/pages/%s/%s%s' % ( section, '/'.join(self.endpath), ext)) values = values or {} if pkg_resources.resource_exists('pylonshq', tmpl_path): if ext == '.mako': return render_to_response( 'pylonshq:%s' % tmpl_path, values, self.request) else: self.c.pagename = ' : '.join( [item.replace('-', ' ').title() for item in self.endpath]) content = pkg_resources.resource_string( 'pylonshq', tmpl_path) body = publish_parts( content, writer_name='html')['html_body'] values={'body':body} return render_to_response( 'pylonshq:templates/rst.mako', values, self.request) raise NotFound()
def sample16(request): clientId = request.POST.get("client_id") privateKey = request.POST.get("private_key") inputFile = request.POST.get("file") url = request.POST.get("url") basePath = request.POST.get("server_type") fileId = request.POST.get("fileId") guid = "" iframe = "" # Checking required parameters if IsNotNull(clientId) == False or IsNotNull(privateKey) == False: return render_to_response("__main__:templates/sample16.pt", {"error": "You do not enter all parameters"}) ### Create Signer, ApiClient and Annotation Api objects # Create signer object signer = GroupDocsRequestSigner(privateKey) # Create apiClient object apiClient = ApiClient(signer) # Create Storage object api = StorageApi(apiClient) if basePath == "": basePath = "https://api.groupdocs.com/v2.0" # Set base path api.basePath = basePath if url != "": try: # Upload file to current user storage using entere URl to the file upload = api.UploadWeb(clientId, url) guid = upload.result.guid fileId = "" except Exception, e: return render_to_response("__main__:templates/sample16.pt", {"error": str(e)})
def sample12(request): clientId = request.POST.get('clientId') privateKey = request.POST.get('privateKey') fileGuId = request.POST.get('fileId') # Checking required parameters if not clientId or not privateKey or not fileGuId: return render_to_response('__main__:templates/sample12.pt', dict(error='You do not enter all parameters')) ### Create Signer, ApiClient and Annotation Api objects # Create signer object signer = GroupDocsRequestSigner(privateKey) # Create apiClient object apiClient = ApiClient(signer) # Create Annotation object ant = AntApi(apiClient) try: # Make a request to Annotation API using clientId and fileGuId response = ant.ListAnnotations(clientId, fileGuId) except Exception, e: return render_to_response('__main__:templates/sample12.pt', dict(error=str(e)))
def get_document(context, request): path = request.path.split('/') if path[-1] == 'edit': docid = path[-2] doc = IDatabase(context).get_document(docid) return render_to_response( "templates/editdocument.pt", { 'title': doc.title, 'body': doc.display(edit=True), 'save_url': doc.url + '/save', 'formid': doc.form.id, 'master': get_renderer('templates/master.pt').implementation(), }, request) elif path[-1] == 'save': docid = path[-2] doc = IDatabase(context).get_document(docid) doc.save(request.params) return HTTPFound( location=doc.url ) else: docid = path[-1] doc = IDatabase(context).get_document(docid) return render_to_response( "templates/opendocument.pt", { 'title': doc.title, 'body': doc.display(), 'master': get_renderer('templates/master.pt').implementation(), }, request)
def picked(request): g = request.registry.settings.get('graph') action = request.matchdict.get('action') format_ = request.matchdict.get('format_') def pickedgraph(): graph = rdflib.Graph() for x in request.session["picked"]: graph += g.triples((x, None, None)) graph += g.triples((None, None, x)) return graph if action == 'download': return serialize(pickedgraph(), format_) elif action == 'rdfgraph': return graphrdf(pickedgraph(), format_) elif action == 'rdfsgraph': return graphrdfs(pickedgraph(), format_) elif action == 'clear': request.session["picked"] = set() return render_to_response( "picked.jinja2", dict(things=[]), request) else: things = [resolve(x) for x in request.session["picked"]] return render_to_response( "picked.jinja2", dict(things=things), request)
def sample02(request): clientId = request.POST.get('client_id') privateKey = request.POST.get('private_key') if IsNotNull(clientId) == False or IsNotNull(privateKey) == False: return render_to_response('__main__:templates/sample02.pt', { 'error' : 'You do not enter you User id or Private key' }) ####Create Signer, ApiClient and Storage Api objects #Create signer object signer = GroupDocsRequestSigner(privateKey) #Create apiClient object apiClient = ApiClient(signer) #Create Storage Api object api = StorageApi(apiClient) try: ####Make a request to Storage API using clientId #Obtaining all Entities from current user files = api.ListEntities(userId = clientId, path = '', pageIndex = 0) #Obtaining file names names = '' for item in files.result.files: #selecting file names names += item.name + '<br>' except Exception, e: return render_to_response('__main__:templates/sample02.pt', { 'error' : str(e) })
def view(request): project = get_selected_project(request) error_id = request.matchdict["id"] try: error = Error.objects(project=project.token, id=error_id).get() except: return HTTPNotFound() error.mark_seen(request.user) error.save() instances = ErrorInstance.objects(hash=error.hash)[:10] params = { "error": error, "selected_project": project, "available_projects": Project.objects(), "instances": instances, "github": GithubLinker(project.github), } try: template = "error-view/" + str(error["language"]).lower() + ".html" return render_to_response(template, params) except: template = "error-view/generic.html" return render_to_response(template, params)
def sample26(request): login = request.POST.get('login') password = request.POST.get('password') if not login or not password: return render_to_response('__main__:templates/sample26.pt', dict(error='You do not enter you login or password')) ####Create Signer, ApiClient and Shared Api objects #Create signer object signer = GroupDocsRequestSigner("123") #Create apiClient object apiClient = ApiClient(signer) #Create Management Api object api = SharedApi(apiClient) #Encode unicode to str encodedPassword = password.encode('utf-8') try: ####Make a request to Management API using clientId userInfo = api.LoginUser(login, encodedPassword) except Exception, e: return render_to_response('__main__:templates/sample26.pt', {'error': str(e)})
def sample15(request): clientId = request.POST.get('clientId') privateKey = request.POST.get('privateKey') # Checking required parameters if not clientId or not privateKey: return render_to_response('__main__:templates/sample15.pt', dict(error='You do not enter all parameters')) ### Create Signer, ApiClient, StorageApi and Document Api objects # Create signer object signer = GroupDocsRequestSigner(privateKey) # Create apiClient object apiClient = ApiClient(signer) # Create DocApi object doc = DocApi(apiClient) # set total views views = 0 try: # Make a request to Document API response = doc.GetDocumentViews(clientId) if response.status == "Ok": views = len(response.result.views) except Exception, e: return render_to_response('__main__:templates/sample15.pt', dict(error=str(e)))
def payment_view(request): echeck = False if 'token' in request.params: # paypal return token = request.params['token'] order = DBSession.query(Order).filter(Order.paypal_token==token).one() paypal = _get_paypal(request.registry.settings) try: result = paypal.get_express_checkout_details(token=token) payerid = result['PAYERID'] result = paypal.do_express_checkout_payment(token=token, payerid=payerid, PAYMENTACTION='SALE', PAYMENTREQUEST_0_PAYMENTACTION='SALE', PAYMENTREQUEST_0_AMT=str(order.total) ) status = result['PAYMENTINFO_0_PAYMENTSTATUS'] if status == 'Completed': order.confirm() elif status == 'Pending' and result['PAYMENTINFO_0_PAYMENTTYPE'] == 'echeck': order.paypal_transaction = result['PAYMENTINFO_0_TRANSACTIONID'] echeck = True else: log.warn(str(result)) return render_to_response('templates/error.pt', {'message': 'PayPal returns: ' + str(result), 'url': request.application_url}) except PayPalAPIResponseError, e: return render_to_response('templates/error.pt', {'message': str(e), 'url': request.application_url})
def login_form_process(self): """Process login form. Render form if attempt_authorize was failed and redirect to root '/' of site. Return form in 'form' key. @todo redirect to request_from url @todo process csrf value""" schema = AuthSchema() form = Form(schema, buttons=('submit',)) if 'submit' in self.request.POST: controls = self.request.POST.items() values = None try: appstruct = form.validate(controls) except ValidationFailure, e: return render_to_response( 'templates/auth_form.jinja2', {'form': e.render()} ) # make here call of attempt_login if self.user_helper.attempt_authorize( appstruct['login'], appstruct['password']): remember(self.request, appsctruct['login']) return HTTPFound("/") else: return render_to_response( 'templates/auth_form.jinja2', {'form':form.render(appstruct=appstruct)} ) return HTTPFound('/')
def sample03(request): clientId = request.POST.get('client_id') privateKey = request.POST.get('private_key') inputFile = request.POST.get('file') # Checking clientId and privateKey if IsNotNull(clientId) == False or IsNotNull(privateKey) == False: return render_to_response('__main__:templates/sample03.pt', { 'error' : 'You do not enter your User Id or Private Key' }) ####Create Signer, ApiClient and Storage Api objects #Create signer object signer = GroupDocsRequestSigner(privateKey) #Create apiClient object apiClient = ApiClient(signer) #Create Storage Api object api = StorageApi(apiClient) try: #A hack to get uploaded file size inputFile.file.seek(0, 2) fileSize = inputFile.file.tell() inputFile.file.seek(0) fs = FileStream.fromStream(inputFile.file, fileSize) ####Make a request to Storage API using clientId #Upload file to current user storage response = api.Upload(clientId, inputFile.filename, fs) #Generation of Embeded Viewer URL with uploaded file GuId iframe = '<iframe src="https://apps.groupdocs.com/document-viewer/embed/' + response.result.guid + '" frameborder="0" width="720" height="600""></iframe>' message = '<p>File was uploaded to GroupDocs. Here you can see your <strong>' + inputFile.filename + '</strong> file in the GroupDocs Embedded Viewer.</p>' except Exception, e: return render_to_response('__main__:templates/sample03.pt', { 'error' : str(e) })
def index(request): if request.method == "POST" and 'username' in request.cookies: username = request.cookies['username'] # TODO process request wishlist = [] for key,value in request.POST.items(): if key.startswith("wish-"): wishlist.append(NAME2WISH[key[5:]]) print("wish={}, value={}".format(key[5:], value)) special = request.params["special"] bequick = request.params["bequick"] print(u"special={}, be quick={}".format(special,bequick)) order = Order(username,request.remote_addr,wishlist,special,bequick) ORDERS[order.id] = order return HTTPFound(location = "/confirm/{}".format(order.id)) else: if 'username' in request.cookies: username = request.cookies['username'] response = render_to_response("pt/index.pt", { "username" : username, "wishbar" : WISHBAR }, request) response.set_cookie('username', value=username, max_age=86400) return response else: return render_to_response('pt/login.pt', {}, request)
def view(request): project = get_selected_project(request) error_id = request.matchdict['id'] try: error = Error.objects(project=project.token, id=error_id).get() except: return HTTPNotFound() error.mark_seen(request.user) error.save() instances = ErrorInstance.objects(hash=error.hash)[:10] params = { 'error': error, 'selected_project': project, 'available_projects': Project.objects(), 'instances': instances, 'github': GithubLinker(project.github) } try: template = 'error-view/' + str(error['language']).lower() + '.html' return render_to_response(template, params) except: template = 'error-view/generic.html' return render_to_response(template, params)
def notallowed(request): auth_userid = authenticated_userid(request) if auth_userid is None: login = LoginView(request) if request.method == 'POST': # Process the login form and redirect view_method = login.post else: # User is not logged in, render the login form view_method = login.get response = view_method() # We need to commit the transaction, so that details about # the forbidden view can be written to the database transaction.commit() if isinstance(response, Response): return response else: return render_to_response("speak_friend:templates/login.pt", response, request=request) else: # If the user is logged in, they don't have permission return render_to_response("speak_friend:templates/403_template.pt", {}, request=request)
def sample08(request): clientId = request.POST.get('client_id') privateKey = request.POST.get('private_key') fileGuId = request.POST.get('fileId') pageNumber = request.POST.get('pageNumber') or 0 #Checking parameters if IsNotNull(clientId) == False or IsNotNull(privateKey) == False or IsNotNull(fileGuId) == False: return render_to_response('__main__:templates/sample08.pt', { 'error' : 'You do not enter all parameters' }) ####Create Signer, ApiClient and Storage Api objects #Create signer object signer = GroupDocsRequestSigner(privateKey) #Create apiClient object apiClient = ApiClient(signer) #Create DocApi object docApi = DocApi(apiClient) ####Make request to DocApi using user id try: #Obtaining URl of entered page url = docApi.GetDocumentPagesImageUrls(clientId, fileGuId, firstPage = int(pageNumber), pageCount = 1, dimension = '600x750') except Exception, e: return render_to_response('__main__:templates/sample08.pt', { 'error' : str(e) })
def model(self, request): """ The method which is used by the api to deliver a machine readable and serializable description of the underlying database table/model. :param request: The request which comes all the way through the application from the client :type request: pyramid.request.Request :param session: The session which is uesed to emit the query. :type session: sqlalchemy.orm.Session :return: An pyramid response object :rtype: pyramid.response.Response :raises: HTTPNotFound """ response_format = request.matchdict['format'] if response_format == 'json': return render_to_response( 'model_restful_json', self.model_description, request=request ) elif response_format == 'xml': return render_to_response( 'model_restful_xml', self.model_description, request=request ) else: text = 'The Format "{format}" is not defined for this service. Sorry...'.format( format=response_format ) log.error(text) raise HTTPNotFound( detail=text )
def sample32(request): clientId = request.POST.get('client_id') privateKey = request.POST.get('private_key') formGuid = request.POST.get('form_guid') templateGuid = request.POST.get('template_guid') callbackUrl = request.POST.get('callbackUrl') basePath = request.POST.get('server_type') email = request.POST.get('email') message = "" # Checking clientId, privateKey and file_Id if IsNotNull(clientId) == False or IsNotNull(privateKey) == False: return render_to_response('__main__:templates/sample32.pt', { 'error' : 'You do not enter all parameters' }) #Get curent work directory currentDir = os.path.dirname(os.path.realpath(__file__)) #Create text file fp = open(currentDir + '/../user_info.txt', 'w') #Write user info to text file fp.write(clientId + "\r\n" + privateKey + "\r\n" + email) fp.close() ####Create Signer, ApiClient and Storage Api objects #Create signer object signer = GroupDocsRequestSigner(privateKey) #Create apiClient object apiClient = ApiClient(signer) #Create Storage Api object signatureApi = SignatureApi(apiClient) #Set base Path if basePath == "": basePath = "https://api.groupdocs.com/v2.0" signatureApi.basePath = basePath #Create webHook and set callback URL webHook = WebhookInfo() webHook.callbackUrl = callbackUrl ####Make a request to Signature API using clientId if formGuid != "": try: #Post form by entered form GUID postForm = signatureApi.PublishSignatureForm(clientId, formGuid, body=webHook) if postForm.status == "Ok": message = '<font color="green">Form is published successfully</font>' #Generate iframe url if basePath == "https://api.groupdocs.com/v2.0": iframe = 'https://apps.groupdocs.com/signature2/forms/signembed/' + formGuid #iframe to dev server elif basePath == "https://dev-api.groupdocs.com/v2.0": iframe = 'https://dev-apps.groupdocs.com/signature2/forms/signembed/' + formGuid #iframe to test server elif basePath == "https://stage-apps-groupdocs.dynabic.com/v2.0": iframe = 'https://stage-apps-groupdocs.dynabic.com/signature2/forms/signembed/' + formGuid elif basePath == "http://realtime-api.groupdocs.com": iframe = 'https://relatime-apps.groupdocs.com/signature2/forms/signembed/' + formGuid iframe = signer.signUrl(iframe) else: raise Exception(postForm.error_message) except Exception, e: return render_to_response('__main__:templates/sample32.pt', { 'error' : str(e) })
def home(req): return render_to_response('templates/lp.html', {}, request=req)
def renderer(request): return render_to_response("template.pt", {"foo": "bar"}, request=request)
#Obtaining file stream of downloading file and definition of folder where to download file currentDir = os.path.dirname(os.path.realpath(__file__)) newpath = currentDir + "/../tmp/" if not os.path.exists(newpath): os.makedirs(newpath) #Downlaoding of file fs = api.GetFile(clientId, file_id); if fs: filePath = newpath + fileName with open(filePath, 'wb') as fp: shutil.copyfileobj(fs.inputStream, fp) message = '<font color="green">File was downloaded to the <font color="blue">' + filePath + '</font> folder</font> <br />'; else: raise Exception('Wrong file ID!') except Exception, e: return render_to_response('__main__:templates/sample04.pt', { 'error' : str(e) }) #If request was successfull - set message variable for template return render_to_response('__main__:templates/sample04.pt', { 'userId' : clientId, 'privateKey' : privateKey, 'file_Id' : file_id, 'message' : message }, request=request)
def home_view(request): """The main view on a discussion""" user_id = request.authenticated_userid or Everyone context = get_default_context(request) discussion = context["discussion"] canRead = user_has_permission(discussion.id, user_id, P_READ) if not canRead and user_id == Everyone: # User isn't logged-in and discussion isn't public: # redirect to login page # need to pass the route to go to *after* login as well # With regards to a next_view, if explicitly stated, then # that is the next view. If not stated, the referer takes # precedence. In case of failure, login redirects to the # discussion which is its context. next_view = request.params.get('next', None) if not next_view and discussion: # If referred here from a post url, want to be able to # send the user back. Usually, Assembl will send the user # here to login on private discussions. referrer = request.url next_view = path_qs(referrer) login_url = get_social_autologin(request, discussion, next_view) if login_url: pass elif next_view: login_url = request.route_url("contextual_react_login", discussion_slug=discussion.slug, _query={"next": next_view}) else: login_url = request.route_url('contextual_react_login', discussion_slug=discussion.slug) return HTTPTemporaryRedirect(login_url) elif not canRead: # User is logged-in but doesn't have access to the discussion # Would use render_to_response, except for the 401 from pyramid_jinja2 import IJinja2Environment jinja_env = request.registry.queryUtility(IJinja2Environment, name='.jinja2') template = jinja_env.get_template('cannot_read_discussion.jinja2') body = template.render(get_default_context(request)) return Response(body, 401) # if the route asks for a post, get post content (because this is needed for meta tags) route_name = request.matched_route.name if route_name == "purl_posts": post_id = FrontendUrls.getRequestedPostId(request) if not post_id: return HTTPSeeOther( request.route_url('home', discussion_slug=discussion.slug)) post = Post.get_instance(post_id) if not post or post.discussion_id != discussion.id: return HTTPSeeOther( request.route_url('home', discussion_slug=discussion.slug)) context['post'] = post elif route_name == "purl_idea": idea_id = FrontendUrls.getRequestedIdeaId(request) if not idea_id: return HTTPSeeOther( request.route_url('home', discussion_slug=discussion.slug)) idea = Idea.get_instance(idea_id) if not idea or idea.discussion_id != discussion.id: return HTTPSeeOther( request.route_url('home', discussion_slug=discussion.slug)) context['idea'] = idea canAddExtract = user_has_permission(discussion.id, user_id, P_ADD_EXTRACT) context['canAddExtract'] = canAddExtract context['canDisplayTabs'] = True preferences = discussion.preferences session = discussion.db if user_id != Everyone: from assembl.models import UserPreferenceCollection # TODO: user may not exist. Case of session with BD change. user = User.get(user_id) preferences = UserPreferenceCollection(user_id, discussion) target_locale = get_locale_from_request(request, session, user) user.is_visiting_discussion(discussion.id) else: target_locale = get_locale_from_request(request, session) translation_service_data = {} try: service = discussion.translation_service() if service.canTranslate is not None: translation_service_data = service.serviceData() except: pass context['translation_service_data_json'] = json.dumps( translation_service_data) locale_labels = json.dumps( DummyGoogleTranslationService.target_locale_labels_cls(target_locale)) context['translation_locale_names_json'] = locale_labels context['preferences_json'] = json.dumps(dict(preferences)) role_names = [x for (x) in session.query(Role.name).all()] context['role_names'] = json.dumps(role_names) response = render_to_response('../../templates/index.jinja2', context, request=request) # Prevent caching the home, especially for proper login/logout response.cache_control.max_age = 0 response.cache_control.prevent_auto = True return response
def assembl_profile(request): session = AgentProfile.default_db localizer = request.localizer profile = get_profile(request) id_type = request.matchdict.get('type').strip() logged_in = request.authenticated_userid save = request.method == 'POST' # if some other user if not profile or not logged_in or logged_in != profile.id: if save: raise HTTPUnauthorized() # Add permissions to view a profile? return render_to_response( 'assembl:templates/view_profile.jinja2', dict(get_default_context(request), profile=profile, user=logged_in and session.query(User).get(logged_in))) confirm_email = request.params.get('confirm_email', None) if confirm_email: return HTTPTemporaryRedirect(location=request.route_url( 'confirm_emailid_sent', email_account_id=int(confirm_email))) errors = [] if save: user_id = profile.id redirect = False username = request.params.get('username', '').strip() if username and (profile.username is None or username != profile.username.username): # check if exists if session.query(Username).filter_by(username=username).count(): errors.append( localizer.translate(_('The username %s is already used')) % (username, )) else: old_username = profile.username if old_username is not None: # free existing username session.delete(old_username) session.flush() # add new username session.add(Username(username=username, user=profile)) if id_type == 'u': redirect = True name = request.params.get('name', '').strip() if name: profile.name = name p1, p2 = (request.params.get('password1', '').strip(), request.params.get('password2', '').strip()) if p1 != p2: errors.append( localizer.translate(_('The passwords are not identical'))) elif p1: profile.password_p = p1 add_email = request.params.get('add_email', '').strip() if add_email: if not is_email(add_email): return dict(get_default_context(request), error=localizer.translate( _("This is not a valid email"))) # No need to check presence since not validated yet email = EmailAccount(email=add_email, profile=profile) session.add(email) if redirect: return HTTPFound(location=request.route_url( 'profile_user', type='u', identifier=username)) profile = session.query(User).get(user_id) unverified_emails = [ (ea, session.query(AbstractAgentAccount).filter_by(email_ci=ea.email_ci, verified=True).first()) for ea in profile.email_accounts if not ea.verified ] get_route = create_get_route(request) providers = get_provider_data(get_route) return render_to_response( 'assembl:templates/profile.jinja2', dict(get_default_context(request), error='<br />'.join(errors), unverified_emails=unverified_emails, providers=providers, providers_json=json.dumps(providers), google_consumer_key=request.registry.settings.get( 'google.consumer_key', ''), the_user=profile, user=session.query(User).get(logged_in)))
def show_login(req): resp = requests.get(REST_SERVER + "/sign_up") return render_to_response(resp, {}, request=req)
def show_users(req): Users = requests.get(REST_SERVER + "/users").json() return render_to_response('templates/show_users.html', {'users': Users}, request=req)
def notfound_view(req): req.response.status = 404 return render_to_response('iap.common:templates/404.jinja2', {'title': '404 Not Found'}, request=req)
def chat(request): try: chat = Session.query(Chat).filter( Chat.url == request.matchdict["url"]).one() except NoResultFound: raise HTTPNotFound own_chat_user = None if request.user is not None and request.user.status != "banned": try: own_chat_user = Session.query(ChatUser).filter( and_( ChatUser.chat_id == chat.id, ChatUser.user_id == request.user.id, )).one() except NoResultFound: pass continuable = chat.status == "ongoing" and own_chat_user is not None # If we can continue the chat and there isn't a page number, show the # full chat window. if ("page" not in request.GET and continuable): own_chat_user.visited = datetime.datetime.now() # Test if we came here from the homepage, for automatically resuming the search. from_homepage = ("HTTP_REFERER" in request.environ and request.environ["HTTP_REFERER"] == request.route_url("home")) message_count = Session.query( func.count('*')).select_from(Message).filter( Message.chat_id == chat.id, ).scalar() if message_count < 30: prompt = None messages = Session.query(Message).filter( Message.chat_id == chat.id, ).order_by(Message.id.asc()).all() else: prompt = Session.query(Message).filter( Message.chat_id == chat.id, ).order_by(Message.id.asc()) prompt = prompt.options(joinedload(Message.user)) prompt = prompt.first() messages = Session.query(Message).filter( Message.chat_id == chat.id, ).order_by( Message.id.desc()).limit(25) messages = messages.options(joinedload(Message.user)) messages = messages.all() messages.reverse() if request.matchdict.get("fmt") == "json": return render_to_response("json", { "chat": chat, "chat_user": own_chat_user, "message_count": message_count, "prompt": prompt, "messages": messages, }, request=request) # List users if we're an admin. # Get this from both message users and chat users, because the latter is # removed if they delete the chat. # XXX DON'T REALLY DELETE CHAT USER WHEN DELETING CHATS. symbol_users = None if request.user is not None and request.user.status == "admin": symbol_users = { _.symbol: _.user for _ in messages if _.user is not None } for chat_user in Session.query(ChatUser).filter( ChatUser.chat_id == chat.id).options( joinedload(ChatUser.user)): symbol_users[chat_user.symbol] = chat_user.user template = "layout2/chat.mako" if request.user.layout_version == 2 else "chat.mako" return render_to_response(template, { "page": "chat", "symbols": symbols, "preset_colours": preset_colours, "chat": chat, "own_chat_user": own_chat_user, "from_homepage": from_homepage, "message_count": message_count, "prompt": prompt, "messages": messages, "symbol_users": symbol_users, }, request=request) # Otherwise show the archive view. # Update the visited time in archive view if the chat is ended. # We need to do this because otherwise it's impossible to mark an ended # chat as read. if chat.status == "ended" and own_chat_user is not None: own_chat_user.visited = datetime.datetime.now() try: current_page = int(request.GET["page"]) except: current_page = 1 messages = Session.query(Message).filter(Message.chat_id == chat.id, ) message_count = Session.query(func.count('*')).select_from(Message).filter( Message.chat_id == chat.id, ) # Hide OOC messages if the chat doesn't belong to us. # Also don't hide OOC messages for admins. if own_chat_user is None and (request.user is None or request.user.status != "admin"): messages = messages.filter(Message.type != "ooc") message_count = message_count.filter(Message.type != "ooc") # Join users if we're an admin. if request.user is not None and request.user.status == "admin": messages = messages.options(joinedload(Message.user)) messages = messages.order_by(Message.id.asc()).limit(25).offset( (current_page - 1) * 25).all() message_count = message_count.scalar() if request.matchdict.get("fmt") == "json": return render_to_response("json", { "chat": chat, "chat_user": own_chat_user, "message_count": message_count, "messages": messages, }, request=request) paginator = paginate.Page( [], page=current_page, items_per_page=25, item_count=message_count, url=paginate.PageURL( request.route_path("chat", url=request.matchdict["url"]), {"page": current_page}), ) # List users if we're an admin. # Get this from both message users and chat users, because the latter is # removed if they delete the chat. # XXX DON'T REALLY DELETE CHAT USER WHEN DELETING CHATS. symbol_users = None if request.user is not None and request.user.status == "admin": symbol_users = { _.symbol: _.user for _ in messages if _.user is not None } for chat_user in Session.query(ChatUser).filter( ChatUser.chat_id == chat.id).options(joinedload( ChatUser.user)): symbol_users[chat_user.symbol] = chat_user.user template = "layout2/chat_archive.mako" if ( request.user is None or request.user.layout_version == 2) else "chat_archive.mako" return render_to_response(template, { "page": "archive", "symbols": symbols, "continuable": continuable, "chat": chat, "own_chat_user": own_chat_user, "messages": messages, "paginator": paginator, "symbol_users": symbol_users, }, request=request)
def enhance(request): check_login(request) session = request.session google_resource_id = "" slideshare_id = "" embed_google = False embed_slideshare = False not_converted = True show_iframe = False form = Form(request, schema=QuestionAnswerSchema) validate_form = form.validate() print form.all_errors() if session.has_key('google-resource-id'): google_resource_id = session['google-resource-id'] if session.has_key('slideshare_id'): slideshare_id = session['slideshare_id'] if fetch_slideshow_status(slideshare_id) == "2": not_converted = False show_iframe = True if google_resource_id != "": embed_google = True if slideshare_id != "": embed_slideshare = True templatePath = "templates/google_ss_preview.pt" if validate_form: introductory_paragraphs = request.POST.get('introductory_paragraphs') question_count = 0 cnxml = session[ "cnxml"] + """<content><section id="intro-section-title"><title id="introtitle">Introduction</title><para id="introduction-1">""" + introductory_paragraphs + """</para></section><section id="slides-embed"><title id="slide-embed-title">View the slides</title><figure id="ss-embed-figure"><media id="slideshare-embed" alt="slideshare-embed"><iframe src="http://www.slideshare.net/slideshow/embed_code/""" + slideshare_id + """" width="425" height="355" /></media></figure></section>""" for i in range(1, 6): form_question = request.POST.get('question-' + str(i)) if form_question: form_radio_answer = request.POST.get( 'radio-' + str(i) ) #this give us something like 'answer-1-1'. so our solution is this question_count += 1 if question_count == 1: cnxml += """<section id="test-section"><title>Test your knowledge</title>""" itemlist = "" for j in range(1, 10): try: form_all_answers = request.POST.get('answer-' + str(i) + '-' + str(j)) if form_all_answers: itemlist += "<item>" + form_all_answers + "</item>" except: print "No element found" if form_radio_answer: solution = request.POST.get(form_radio_answer) cnxml += """<exercise id="exercise-""" + str( i ) + """"><problem id="problem-""" + str( i ) + """"><para id="para-""" + str(i) + """">""" + str( form_question ) + """<list id="option-list-""" + str( i ) + """" list-type="enumerated" number-style="lower-alpha">""" + str( itemlist) + """</list></para></problem>""" else: print "ELESE CONDUITION OF radio" solution = request.POST.get('answer-' + str(i) + '-1') cnxml += """<exercise id="exercise-""" + str( i) + """"><problem id="problem-""" + str( i) + """"><para id="para-""" + str( i) + """">""" + str( form_question) + """</para></problem>""" print "FORM RADIO ANSWER", form_radio_answer print "SOLUTION", solution cnxml += """ <solution id="solution-""" + str( i ) + """"> <para id="solution-para-""" + str( i ) + """">""" + solution + """</para></solution></exercise>""" """form_solution = request.POST.get('solution-'+str(i)) all_post_data = {"data":{"options":form_options,"solution":form_solution,"question":form_question}} for question in all_post_data: options = all_post_data[question]['options'] solution = all_post_data[question]['solution'] asked_question = all_post_data[question]['question'] optionlist="" for option in options: optionlist+="<item>"+option+"</item>""" #cnxml+="""<exercise id="exercise-"""+str(j)+""""><problem id="problem-"""+str(j)+""""><para id="para-"""+str(j)+"""">"""+str(asked_question)+"""<list id="option-list-"""+str(j)+"""" list-type="enumerated" number-style="lower-alpha">"""+str(optionlist)+"""</list></para></problem>""" #cnxml+=""" <solution id="solution-"""+str(j)+""""> <para id="solution-para-"""+str(j)+"""">"""+solution+"""</para></solution></exercise>""" #j+=1 metadata = session['metadata'] if question_count >= 1: cnxml += "</section></content></document>" else: cnxml += "</content></document>" workspaces = [(i['href'], i['title']) for i in session['login'].collections] metadata_entry = sword2cnx.MetaData(metadata) zipped_filepath = session['userfilepath'] zip_archive = zipfile.ZipFile(zipped_filepath, 'w') zip_archive.writestr("index.cnxml", cnxml) zip_archive.close() conn = sword2cnx.Connection("http://cnx.org/sword/servicedocument", user_name=session['login'].username, user_pass=session['login'].password, always_authenticate=True, download_service_document=True) collections = [{ 'title': i.title, 'href': i.href } for i in sword2cnx.get_workspaces(conn)] session['login'].collections = collections workspaces = [(i['href'], i['title']) for i in session['login'].collections] session['workspaces'] = workspaces with open(zipped_filepath, 'rb') as zip_file: deposit_receipt = conn.create( col_iri=workspaces[0][0], metadata_entry=metadata_entry, payload=zip_file, filename='upload.zip', mimetype='application/zip', packaging='http://purl.org/net/sword/package/SimpleZip', in_progress=True) session['dr'] = deposit_receipt session['deposit_receipt'] = deposit_receipt.to_xml() soup = BeautifulSoup(deposit_receipt.to_xml()) data = soup.find("link", rel="edit") edit_iri = data['href'] session['edit_iri'] = edit_iri creator = soup.find('dcterms:creator') username = session['login'].username email = creator["oerdc:email"] url = "http://connexions-oerpub.appspot.com/" post_values = { "username": username, "email": email, "slideshow_id": slideshare_id } data = urllib.urlencode(post_values) google_req = urllib2.Request(url, data) google_response = urllib2.urlopen(google_req) now_string = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') temp_dir_name = '%s-%s' % (request.session['login'].username, now_string) save_dir = os.path.join(request.registry.settings['transform_dir'], temp_dir_name) os.mkdir(save_dir) request.session['upload_dir'] = temp_dir_name cnxml = clean_cnxml(cnxml) save_cnxml(save_dir, cnxml, []) return HTTPFound(location=request.route_url('metadata')) #return HTTPFound(location=request.route_url('updatecnx')) response = { 'form': FormRenderer(form), "slideshare_id": slideshare_id, "google_resource_id": google_resource_id, "embed_google": embed_google, "embed_slideshare": embed_slideshare, "not_converted": not_converted, "show_iframe": show_iframe } return render_to_response(templatePath, response, request=request)
def api_doc(request): return render_to_response(TEMPLATE_ROOT + 'sgd_redoc.jinja2', {}, request=request)
def chat_list(request): current_page = int(request.GET.get("page", 1)) if request.matched_route.name.startswith("chat_list_unanswered"): current_status = "unanswered" elif request.matched_route.name.startswith("chat_list_ongoing"): current_status = "ongoing" elif request.matched_route.name.startswith("chat_list_ended"): current_status = "ended" else: current_status = None if request.matched_route.name.startswith("chat_list_label"): current_label = request.matchdict["label"].lower().strip().replace( " ", "_") if current_label != request.matchdict["label"]: raise HTTPFound( request.route_path("chat_list_label", label=current_label)) else: current_label = None chats = Session.query(ChatUser, Chat, Message).join(Chat).outerjoin( Message, Message.id == Session.query(func.min(Message.id), ).filter( Message.chat_id == Chat.id, ).correlate(Chat), ).filter(ChatUser.user_id == request.user.id, ) chat_count = Session.query(func.count('*')).select_from(ChatUser).filter( ChatUser.user_id == request.user.id, ) if current_status == "unanswered": chats = chats.filter( and_( Chat.last_user_id is not None, Chat.last_user_id != request.user.id, )) chat_count = chat_count.join(Chat).filter( and_( Chat.last_user_id is not None, Chat.last_user_id != request.user.id, )) elif current_status is not None: chats = chats.filter(Chat.status == current_status) chat_count = chat_count.join(Chat).filter( Chat.status == current_status) if current_label is not None: label_array = cast([current_label], ARRAY(Unicode(500))) chats = chats.filter(ChatUser.labels.contains(label_array)) chat_count = chat_count.filter(ChatUser.labels.contains(label_array)) chats = chats.order_by(Chat.updated.desc()).limit(25).offset( (current_page - 1) * 25).all() # 404 on empty pages, unless it's the first page. if current_page != 1 and len(chats) == 0: raise HTTPNotFound chat_count = chat_count.scalar() if request.matchdict.get("fmt") == "json": return render_to_response("json", { "chats": [{ "chat_user": chat_user, "chat": chat, "prompt": prompt, } for chat_user, chat, prompt in chats], "chat_count": chat_count, }, request=request) paginator = paginate.Page( [], page=current_page, items_per_page=25, item_count=chat_count, url=paginate.PageURL( request.route_path(request.matched_route.name, label=current_label), {"page": current_page}), ) labels = (Session.query( func.unnest(ChatUser.labels), func.count("*")).filter(ChatUser.user_id == request.user.id).group_by( func.unnest(ChatUser.labels)).order_by( func.count("*").desc(), func.unnest(ChatUser.labels).asc()).all()) template = "layout2/chat_list.mako" if request.user.layout_version == 2 else "chat_list.mako" return render_to_response(template, { "chats": chats, "paginator": paginator, "labels": labels, "current_status": current_status, "current_label": current_label, "symbols": symbols, }, request=request)
def error(self, request): request.response.status = 500 return render_to_response(TEMPLATE_ROOT + 'error.jinja2', {}, request=request)
def blast_fungal(request): return render_to_response(TEMPLATE_ROOT + 'blast_fungal.jinja2', {}, request=request)
def suggestion(request): return render_to_response(TEMPLATE_ROOT + 'suggestion.jinja2', {}, request=request)
def primer3(request): return render_to_response(TEMPLATE_ROOT + 'primer3.jinja2', {}, request=request)
def snapshot(request): return render_to_response(TEMPLATE_ROOT + 'snapshot.jinja2', {}, request=request)
def variant_viewer(request): return render_to_response(TEMPLATE_ROOT + 'variant_viewer.jinja2', {}, request=request)
def references_this_week(request): page = {} return render_to_response(TEMPLATE_ROOT + 'references_this_week.jinja2', page, request=request)
def style_guide(request): return render_to_response(TEMPLATE_ROOT + 'style_guide.jinja2', {}, request=request)
def downloads_tree(request): return render_to_response(TEMPLATE_ROOT + 'downloads.jinja2', {}, request=request)
def not_found(request): request.response.status = 404 return render_to_response(TEMPLATE_ROOT + 'lost.jinja2', {}, request=request)
def api_portal(request): return render_to_response(TEMPLATE_ROOT + 'swagger.jinja2', {}, request=request)
def interaction_search(request): return render_to_response(TEMPLATE_ROOT + 'interaction_search.jinja2', {}, request=request)
def goslimmapper(request): return render_to_response(TEMPLATE_ROOT + 'goSlimMapper.jinja2', {}, request=request)
def colleague_show(request): return render_to_response(TEMPLATE_ROOT + 'misc.jinja2', {}, request=request)
if inputFile != "": try: #A hack to get uploaded file size inputFile.file.seek(0, 2) fileSize = inputFile.file.tell() inputFile.file.seek(0) fs = FileStream.fromStream(inputFile.file, fileSize) ####Make a request to Storage API using clientId #Upload file to current user storage response = api.Upload(clientId, inputFile.filename, fs) guid = response.result.guid fileId = "" except Exception, e: return render_to_response('__main__:templates/sample09.pt', {'error': str(e)}) if fileId != '': guid = fileId #Generation of iframe URL using fileGuId if iframeType == "viewer": if basePath == "https://api.groupdocs.com/v2.0": iframe_url = 'https://apps.groupdocs.com/document-viewer/embed/' + guid #iframe to dev server elif basePath == "https://dev-api.groupdocs.com/v2.0": iframe_url = 'https://dev-apps.groupdocs.com/document-viewer/embed/' + guid #iframe to test server elif basePath == "https://stage-api.groupdocs.com/v2.0": iframe_url = 'https://stage-apps.groupdocs.com/document-viewer/embed/' + guid #Iframe to realtime server elif basePath == "http://realtime-api.groupdocs.com": iframe_url = 'https://realtime-apps.groupdocs.com/document-viewer/embed/' + guid
def strain_alignment(request): return render_to_response(TEMPLATE_ROOT + 'strainAlignment.jinja2', {}, request=request)
# Make a request to Storage API list = storageApi.ListEntities(clientId, newPath) if list.status == "Ok": for folder in list.result.folders: if (folder.name == last): folderId = folder.id ### Get list of shares if folderId is not None: # Make a request to Document API shares = docApi.GetFolderSharers(clientId, int(folderId)) if shares.status == "Ok" and len(shares.result.shared_users) > 0: for x in xrange(len(shares.result.shared_users)): # construct users list users += str(shares.result.shared_users[x].nickname) if x != len(shares.result.shared_users) - 1: users += ", " except Exception, e: return render_to_response('__main__:templates/sample14.pt', {'error': str(e)}) # If request was successfull - set variables for template return render_to_response('__main__:templates/sample14.pt', { 'userId': clientId, 'privateKey': privateKey, 'path': path, 'users': users }, request=request)
def gotermfinder(request): return render_to_response(TEMPLATE_ROOT + 'goTermFinder.jinja2', {}, request=request)