def make_request_context(dic=None): from limited.utils import widgets from models import Page, Tag, User from viewutils import get_latest_comments if dic is None: dic = {} static_files = GroupedDict(find_static_files()) dic.update((key, getattr(settings, key)) for key in ("BLOG_URL", "MEDIA_URL", "ADMINS", "USE_PYGMENTS")) dic.update(DEFAULT_CONTEXT_VARIABLES) dic.update( { "navigation_top": [HomePage()] + list(Page.filter(in_navigation=True)), "tags": Tag.objects.all().order_by("-name"), "latestcomments": get_latest_comments(), "popular_pages": Page.filter(popular=True), "WIDGETS": widgets.get_widgets(), "JS_FILES": static_files["js"], "CSS_FILES": static_files["css"], "limited": _internal.software_info(), } ) if not "COPYRIGHT_YEARS" in dic: from datetime import datetime dic["COPYRIGHT_YEARS"] = [datetime.now().year] assert 0 < len(dic["COPYRIGHT_YEARS"]) < 3 # two years at maximum return dic
async def index_post(request: Request, url: str = Form(..., max_length=255), depth: int = Form(...)): parsed_url = urlparse(url) err_msg = list() if not parsed_url.scheme or not parsed_url.netloc: err_msg.append("URL validation error") if not depth or depth > 3: err_msg.append("Invalid depth value (allowed values 1-3)") if err_msg: return templates.TemplateResponse( "index.html", { "request": request, "errMsg": ", ".join(err_msg) }, status_code=status.HTTP_400_BAD_REQUEST) sources = await parse_url(url, depth) try: if len(sources) > 1: Page.save_many(sources) else: Page(**sources[0]) except Exception as error: return templates.TemplateResponse( "index.html", { "request": request, "errMsg": f'{error}' }, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) return templates.TemplateResponse("index.html", { "request": request, "message": "Indexing complete" }, status_code=status.HTTP_201_CREATED)
def edit(request, name): """Allows users to edit wiki pages.""" try: page = Page.objects.get(name=name) except Page.DoesNotExist: page = None if request.method == "POST": form = PageForm(request.POST) if form.is_valid(): if not page: page = Page() page.name = form.cleaned_data["name"] page.content = form.cleaned_data["content"] page.save() return HttpResponseRedirect("../../%s/" % page.name) else: if page: form = PageForm(initial=page.__dict__) else: form = PageForm(initial={"name": name}) return render_to_response( "wiki/edit.html", { "form": form, "admin": is_admin(request), "user": get_user(request), "navbar": Page.objects.get(name="NavBar"), }, )
def contentapp(request, resourceName): response = "<h1> WELLCOME TO THE JUNGLE! </h1>" if request.user.is_authenticated(): logged = "<br><br>Logged in as " + request.user.username +\ ". <a href='/admin/logout/'>Logout</a><br>" if request.method == "GET": try: info = Page.objects.get(name=resourceName) return HttpResponse(response + info.contenido) except Page.DoesNotExist: response += '<body> Valor no encontrado, definalo </body>' form = "<form action='' method='POST'>\n" form += "Nombre: <input type='text' name='name' value='" + resourceName + "'><br>\n" form += "Contenido: <input type='text' name='contenido'><br>\n" form += "<input type='submit' value='enviar'>\n" form += "</form>\n" response += form response += "<a href='./admin'>Ver Base de datos</a>" return HttpResponse(response) elif request.method == "POST": response += '<body> POST </body>' newPage = Page(name=request.POST['name'], contenido=request.POST['contenido']) newPage.save() response += "Nombre: " + request.POST['name'] response += ", Contenido: " + request.POST['contenido'] return HttpResponse(response) else: response += '<body> No way </body>' return HttpResponse(response) else: logged = "<br><br>Not logged. <a href='/admin/login/'>Login</a><br>" return HttpResponse(response + logged)
def addPage(name, content): try: newPage = Page.objects.get(name=name) newPage.page = content except Page.DoesNotExist: newPage = Page(name = name, page = content) newPage.save()
def css(page_key): preview = ('preview' in request.args) and (request.args.get('preview') != '0') pretty = ('pretty' in request.args) and (request.args.get('pretty') != '0') if not preview and not pretty: count_view('css:all') if request.referrer: count_view('css:page:%s:%s' % (urlparse(request.referrer).netloc, page_key)) etag = memcache.get(page_key + '-css-etag') if etag and request.headers.get('If-None-Match', '') == etag: return 'Not Modified', 304 css = memcache.get(page_key + '-css') if not css or not etag: page = Page.get_or_404(page_key) css = page.compressed_css(False) etag = _etag(css) expires = 24 * 60 * 60 memcache.set(page_key + '-css-etag', etag, time=expires) memcache.set(page_key + '-css', css, time=expires) return _send_file(css, 'text/css', etag) else: page = Page.get_or_404(page_key) if pretty: css = page.uncompressed_css(preview) else: css = page.compressed_css(preview) return _send_file(css, 'text/css')
def create_default_page(page_title): default_text = ('This page is brand new. ' + 'You can edit it by clicking the link above.') page = Page(title=page_title, text=default_text) page.put() return page
def edit(request, name): """Allows users to edit wiki pages.""" try: page = Page.objects.get(name=name) except Page.DoesNotExist: page = None if request.method == 'POST': form = PageForm(request.POST) if form.is_valid(): if not page: page = Page() page.name = form.cleaned_data['name'] page.content = form.cleaned_data['content'] page.save() return redirect(view, name=page.name) else: if page: form = PageForm(initial=page.__dict__) else: form = PageForm(initial={'name': name}) context = { 'form': form, } return render_to_response('wiki/edit.html', RequestContext(request, context))
def edit(request, slug): params = {"slug": slug} page = get_or_none(Page, slug=slug) text = page.current_revision.text if page and page.current_revision else "" form = EditForm(data=request.POST or None, initial={"text": text}) if request.method == "POST" and form.is_valid(): if not page: page = Page(title=unslugify(slug), slug=slug) page.save() form.save(page, request.user) return redirect(reverse("wiki-detail", kwargs={"slug": page.slug})) params["form"] = form if page: params["action"] = "Edit" params["title"] = page.title params["modified"] = page.modified_on params["action"] = "Edit" else: params["title"] = unslugify(slug) params["modified"] = "NULL" params["action"] = "Create" return render(request, "edit.html", params)
def get(self, name): """Handles the get requests for edit page of the wiki pages The user will get redirected to the SignupPage if authentication fails. If a version is specified in the url it retreives the corresponding version of the requested page. If the version doesn't exists, it redirects to the requested edit page without a version specified. If no version is specified the latest version of the page will be retreived to be displayed. If there is no version of the page in the datastore, the requested name will be transformed and used for Page.name. """ self.restrictedArea() name = utils.checkPage(name) version = self.request.get('v') version = 0 if not version else int(version) page = Page.getName(name, version) if not page and version: self.redirect('/_edit/%s' % name) return None if not page and not version: page = Page.createPage(name) params = { 'page': page } self.render(settings.TEMPLATE_FILENAME['edit'], **params)
def main(): """ Main command-line function. """ name = 'Testing' label = Label.objects(name=name).upsert_one(name=name) lines = lib.read('var/chrome_onetab.txt') pages = [ dict(zip(('url', 'title'), line.split(' | ', 1))) for line in lines ] for page in pages[:10]: url = page['url'] print(url) resp = requests.get(url) print(resp.status_code, resp.reason) body = resp.text print(len(body)) page_rec = Page( title=page['title'], url=url, content=body, status_code=resp.status_code, label=label, ) page_rec.save() print()
def _create_example_site(user): site = Site( name='Example Site', owner=user, users=[user], admins=[user], example=True, ) site.put() for v in [4, 5]: name = 'Html%d Example' % v style = Style(site=site, name=name) style.put() rev = StyleRevision(parent=style, rev=0) rev.put() rev.update(render_template('examples/blog-html%d.css' % v)) style.published_rev = rev rev = StyleRevision(parent=style, rev=1) rev.put() rev.update(render_template('examples/blog-html%d-preview.css' % v)) style.preview_rev = rev style.put() page = Page(site=site, name=name, url=url_for('example%d' % v, page_key=0, _external=True), _styles=[style.key()]) page.put() page.url = url_for('example%d' % v, page_key=page.key(), _external=True) page.put() page.queue_refresh()
def test_page_app_name_after_save(self): p = Page() p.save() self.assertEqual(p.app_model, 'pages.Page', 'Value for app_model is not correct after save.') self.assertEqual(p.get_app_model(), 'pages.Page', 'Value for get_app_model() is not correct after save.')
def post(self, slug=None): f = page_form() data = self.get_arguments() is_edit = data.has_key('ori_slug') _ = self._ try: attachments = self.get_argument('attachments', None) if attachments: data['attachments'] = parse_attachments( data['attachments'], is_edit) if f.validates(tornado.web._O(data)): page = Page.one({'type': 'Page', 'slug': data['ori_slug']}) \ if is_edit else Page() page.save(data, user=self.current_user) if attachments: page['attachments'] = move_attachments( self.settings.upload_path, data['attachments']) page.update_html() page.save() self.set_flash(_("Page has been saved.")) self.redirect(page.get_url()) return page = Page() raise Exception(_("Invalid form data.")) except Exception, e: if attachments: page['attachments'] = data['attachments'] f.note = f.note if f.note else e self.render("page-edit", f=f, page=page, user=self.current_user)
def processCmsRequest(request, resource): if request.user.is_authenticated(): loged = "<br><br>Logged in as " + request.user.username +\ ". <a href='/admin/logout/'>Logout</a><br>" else: loged = "<br><br>Not logged. <a href='/admin/login/'>Login</a><br>" if request.method == 'GET': try: page = Page.objects.get(name=resource) return HttpResponse(page.page + loged) except Page.DoesNotExist: return HttpResponseNotFound("Page not found" + loged) elif request.method == 'PUT': if request.user.is_authenticated(): try: newPage = Page.objects.get(name=resource) newPage.page = request.body except Page.DoesNotExist: newPage = Page(name = resource, page = request.body) newPage.save() return HttpResponse("Added to the list") else: return HttpResponse("Couldn't add to the list" + loged) else: return HttpResponse(status=403)
def get_object(self, request, region='', slug=''): self.setup_region(region) obj = Page(slug=slugify(slug), region=self.region) obj.title = obj.versions.most_recent().name obj.page = obj return obj
def save(self, *args, **kwargs): cd = self.cleaned_data pid = cd.pop('parent', '') parent = Page.objects.get(pk=pid) if pid else None if self.instance.pk is None: if parent: self.instance = parent.add_child(**cd) self.instance.move(parent, pos='first-child') else: self.instance = Page.add_root(**cd) else: previous_parent = self.instance.get_parent() self.instance.save() if parent != previous_parent: if parent: self.instance.move(parent, pos='first-child') else: self.instance.move(Page.get_first_root_node(), pos='first-sibling') self.instance = Page.objects.get(pk=self.instance.pk) super(PageForm, self).save(*args, **kwargs) return self.instance
def testBlogPaginate(self): """Test view and template of a paginated blog Must have : - "Previous" link - "Next" link - Antichronological order """ # Populate blog with temporary content temp = [] for i in range(30): a = Page(title="temp_%s" % i, slug="temp-%s" % i, parent=self.blog21, folder_type=0, publish_state=Page.PUBLISHED ) a.save() temp += [a] # Test Page 1 response = self.client.get(urlblog('categ_2-fr/blog_21-fr', 1)) self.assertEqual(response.status_code, 200) self.assertContains(response, temp[29].get_title()) self.assertContains(response, urlblog('categ_2-fr/blog_21-fr', 2)) # Previous link self.assertNotContains(response, temp[1].get_title()) # Test page 3 response = self.client.get(urlblog('categ_2-fr/blog_21-fr', 3)) self.assertEqual(response.status_code, 200) self.assertContains(response, urlblog('categ_2-fr/blog_21-fr', 2)) # Previous link self.assertContains(response, urlblog('categ_2-fr/blog_21-fr', 4)) # Next Link self.assertNotContains(response, temp[29].get_title()) self.assertContains(response, temp[19].get_title())
def edit_page(request, page_slug=WIKI_DEFAULT_PAGE, design_slug=WIKI_DEFAULT_DESIGN): try: page = Page.objects.get(slug__iexact=page_slug) except Page.DoesNotExist: page = Page(slug=page_slug, title=page_slug, content="Click edit to change the page") page.save() try: design = Design.objects.get(slug__iexact=design_slug) except Design.DoesNotExist: raise Http404 template = os.path.join(design.path, "edit.html") if design_slug != WIKI_DEFAULT_DESIGN: view_page = WIKI_PREFIX_URL + "%s/%s" % (design_slug, page_slug) else: view_page = WIKI_PREFIX_URL + "%s" % (page_slug) if not page.editable: return HttpResponseRedirect(view_page) return create_update.update_object( request, form_class=PageForm, object_id=page.id, post_save_redirect=view_page, template_name=template, template_object_name="page", extra_context={ "design": design, "media_url": WIKI_PREFIX_URL + "site_media/" + design_slug, "wiki_url": WIKI_PREFIX_URL, }, )
def test_step4_switch_project(self, browser, baseurl, private_project): project = private_project page_object = Page(browser, baseurl) page_object.switch_project(project) assert project == page_object.get_project_name()
def main(request, resource): if request.user.is_authenticated(): logged = ("Logged in as " + request.user.username + " <a href='/admin/logout/'>Log out</a>") else: logged = ("Not logged in. " + "<a href='/admin/login/?next=/admin/'>Log in</a>") if request.method == "GET": try: page_entry = Page.objects.get(name=resource) return HttpResponse(logged + "<br/>" + page_entry.page) except Page.DoesNotExist: if resource == "": resource = "Main Page" return HttpResponseNotFound(logged + "<br/>" + "Page not found: %s." % resource) elif request.method == "PUT": new_entry = Page(name=resource, page=request.body) new_entry.save() return HttpResponse(logged + "<br/>" + "Succesful PUT operation: " + request.body) else: return HttpResponseForbidden(logged + "<br/>" + "Operation not available")
def load(): first_page = Page(url="http://www.example.com") first_page_key = first_page.put() first_q = Question( q="איפה זה האזור הממוזג?", who="קובי", page=first_page_key, answers=[ Answer(a="אנא עארף?", who="בניד"), Answer( a="לא יודע, אבל נשמע נעים", who="יוסי", ), ], ).put_async() second_q = Question( q="מה היה הנזק מסופת הטורנדו החזקה בהיסטוריה?", who="קובי", page=first_page_key, answers=[ Answer( a="לא יודע", who="בניד", ), ], ).put_async()
def mostrar(request, resource): salida = "" if request.user.is_authenticated(): salida += "<p>Hi " + request.user.username + ". " salida += "<a href='/logout/'>Logout</a></p>" else: salida += "<p>You aren't logged in. " salida += "<a href='/admin/login/'>Login!</a></p>" if request.method == "GET": try: fila = Page.objects.get(name=resource) return HttpResponse(salida + fila.page) except Page.DoesNotExist: return HttpResponseNotFound(salida + 'Page not found: ' + resource) except Page.MultipleObjectsReturned: return HttpResponseNotFound(salida + 'Server allocated more than \ one page for that resource') elif request.method == "PUT": if request.user.is_authenticated(): newpage = Page(name=resource, page=request.body) newpage.save() return HttpResponse(salida + "New page added:\n" + request.body) else: salida += "YOU MUST <a href='/admin/login/'>LOG IN</a>" return HttpResponse(salida) else: return HttpResponseForbidden(salida + "Method not allowed")
def inicio(request): if request.method == "POST": url = request.POST.get('url') url = procUrl(url) try: encontrada = Page.objects.get(url_original=url) except Page.DoesNotExist: pag = Page(url_original=url) pag.save() encontrada = Page.objects.get(url_original=url) respuesta = '<a href ="' + str(encontrada.id) + '">' respuesta += "http://localhost:1234/" + str(encontrada.id) + '</a>' return HttpResponse(respuesta) listado = Page.objects.all() respuesta = "<ol>" for elemento in listado: respuesta += '<li><a href ="' + str(elemento.url_original) + '">' respuesta += str(elemento.url_original) + '</a>' + " = " respuesta += '<a href="' + str(elemento.id) + '">' respuesta += "http://localhost:1234/" + str(elemento.id) + '</a>' respuesta += "</ol>" template = get_template("pag.html") argumentos = { 'contenido': respuesta, } return HttpResponse(template.render(Context(argumentos)))
def get(self, title): # check the user identity cookie_val = self.request.cookies.get('user_id') #check whether it is login user username = checkUser(cookie_val) if username: #check whether the request has version para in it page=None version = self.request.get("v") if version: if version.isdigit(): page = Page.get_by_id(int(version)) if page: page=[page] else: self.error("404") return else: self.error("404") return # check whether the page has been created else: query = Page.fetchPages(title) page = query.fetch(1) if page: self.render_front(username=username,title=title,content=page[0].content) else: self.render_front(username=username,title=title) else: self.redirect("/")
def index(request): params = {} if settings.SHOWPAGES: pages = Page.all() pages.order("-modified") posts = pages.fetch(settings.SHOWPAGES) params['posts'] = posts return respond(request, 'base.html', params) else: home_category = 'Main' home_page = 'Home' page = db.GqlQuery("SELECT * FROM Page WHERE name = :1", home_page).get() if page == None: if users.get_current_user(): category = db.GqlQuery("SELECT * FROM Category WHERE name = :1", home_category).get() if category == None: category = Category(name=home_category, sequence=1) category.put() page = Page(name=home_page, category=home_category, sequence=1, content='<h1>Home Page</h1><h5>Change me!</h5>') page.put() else: return HttpResponseRedirect(users.create_login_url(request.get_full_path())) return viewPage(request, 'Main', 'Home')
def wiki(user_slug, wiki_slug): """ Renders a wiki's main page. -> user's slugified name; wiki's slugified title """ try: user = User.get_by(name_slug=user_slug) except NoResultFound: flash("This user does not exist,<br />\ and consequently, their wiki does not either.") return redirect(url_for('main')) try: wiki = user.wiki_by_slug(wiki_slug) except NoResultFound: if user_slug == g.user.name_slug: flash("This wiki does not exist.") else: flash("This wiki either is private or does not exist.") return redirect(url_for('main')) if request.method == 'POST': title = request.form['title'] try: Page.get_by(title_slug=slugify(title)) except NoResultFound: page = Page(wiki=wiki, title=title, title_slug=slugify(title), content="<h1>%s</h1><p></p>" % title) models.session.commit() return redirect(url_for('wiki_page', user_slug=user.name_slug, wiki_slug=wiki.title_slug, page_slug=slugify(title))) else: page = wiki.page_by_slug(wiki_slug) if wiki.permission_to_view(g.user): return render_template('page.html', user=user, wiki=wiki, page=page) else: flash("This wiki either is private or doesn't exist.") return redirect(url_for('main'))
def get(self, name): """Handles the get requests for the wiki pages If a version is specified in the url it retreives the corresponding version of the requested page. If the version doesn't exists, it redirects to the requested page without a version specified. If no version is specified the latest version of the page will be retreived to be displayed. If there is no version of the page in the datastore, the user will be redirected to '/_edit' which will be handled by EditPage. """ name = utils.checkPage(name) version = self.checkVersionRequest() page = Page.getName(name, version) last_pages = Page.getLast(10) if page: params = { 'page': page, 'last_pages': last_pages } self.render(settings.TEMPLATE_FILENAME['wiki'], **params) else: if version: self.redirect('/%s' % name) else: self.redirect('/_edit/%s' % name)
def create_page(db, page): new_data = Page() new_data.title = unicode(page['title']) new_data.content = unicode(page["content"]) new_data.css = unicode(page['css']) new_data.book_id = int(page["book_id"]) db.session.add(new_data)
def contentapp(request,resourceName): response = "<h1> WELLCOME TO THE JUNGLE! </h1>" if request.method == "GET": try: info = Page.objects.get(name=resourceName) return HttpResponse(response + info.contenido) except Page.DoesNotExist: response += '<body> Valor no encontrado, definalo </body>' form = "<form action='' method='POST'>\n" form += "Nombre: <input type='text' name='name' value='" + resourceName + "'><br>\n" form += "Contenido: <input type='text' name='contenido'><br>\n" form += "<input type='submit' value='enviar'>\n" form += "</form>\n" response += form return HttpResponse(response) elif request.method == "POST": response += '<body> POST </body>' newPage = Page(name=request.POST['name'], contenido=request.POST['contenido']) newPage.save() response += "Nombre: " + request.POST['name'] response += ", Contenido: " + request.POST['contenido'] return HttpResponse(response) else: response += '<body> No way </body>' return HttpResponse(response)
def post(self,slug): page = Page.query(Page.slug == slug).get() if page: page.slug = slug page.title = self.request.get('title') page.text = self.request.get('text') page.prev = self.request.get('prev') page.next = self.request.get('next') page.doc = self.request.get('doc') page.allowed = int(self.request.get('level')) page.put() self.redirect('/content/{}'.format(slug)) else: page = Page(title = self.request.get('title'), slug = slug, author = users.get_current_user(), text = self.request.get('text'), prev = self.request.get('prev'), next = self.request.get('next'), doc = self.request.get('doc'), allowed = int(self.request.get('level')) ) page.put() self.redirect('/content/{}'.format(slug))
def updatePageDB(title): current_page = Page.query.filter_by(name=title).first() if current_page is None: current_page = Page(title) else: current_page.visitPage() db.session.add(current_page) db.session.commit()
def test_page_content_ptr_app_name(self): p = Page() p.save() c = p.content_ptr self.assertEqual(c.app_model, 'pages.Page', 'Value for content.app_model is not correct.') self.assertEqual(c.get_app_model(), 'pages.Page', 'Value for get_app_model() is not correct after save.')
def save_page(language, query, link, rank, title): try: pg = Page.create(language=language, query=query, link=link, rank=rank, title=title) except peewee.IntegrityError: pg = Page.get(Page.language == language, Page.link == link, Page.query == query) pg.language = language pg.rank = rank pg.title = title pg.save()
def page_update_or_create(name, content): """Update or create a Wiki Page""" try: p = Page.objects.get(name=name) except Page.DoesNotExist: p = Page(name=name) finally: p.content = content p.save()
def get(self, tag): self.response.headers['Content-Type'] = 'text/html' pages = Page.query_by_tag(tag).fetch() tag_page = Page.query_by_slug('0-tags-page').get() if not pages or not tag_page: self.response.write('Tag not found.') return (title, tags, html) = parse_landing_page(tag_page.content, pages) self.response.write(html)
def add_pages(): for style in Style.all(): page = Page( name = style.name, url = style.url, site = style.site, _styles = [style.key()], ) page.put()
def post(self, page_title, revision=None): user = self.authenticate_session_id() page_title = page_title.strip('/') content = self.request.get("content") # content = autolink_html(content) # cleaner = Cleaner(remove_tags=["p", "div"]) # content = cleaner.clean_html(content) Page.new_revision(page_title, content, user.username) self.redirect("/" + page_title)
def addPage(resource, body): try: Page.objects.get(name=resource) salida = "That page was in the server" except Page.DoesNotExist: newpage = Page(name=resource, page=body) newpage.save() salida = "New page added" return salida
def get_page(self, page): """Return a single page from the cloud store, storing it locally""" if not self.token: log.debug("No token") return None # get the folder contents metadata = self.get_metadata(page) if not metadata: return None markup = None for i in metadata['contents']: if not i['is_dir']: if os.path.basename(i['path']) in self.valid_indexes: markup = i['path'] break if not markup: return None get_url = _urls.files % (markup, urllib.urlencode({"access_token": self.token})) log.debug(get_url) r = fetch(get_url) if r['status'] == 200: metadata = json.loads(r['x-dropbox-metadata']) try: headers, body, mime_type = parse_rfc822(r['data']) except Exception as e: log.error("Could not parse %s: %s" % (page, e)) return None # mtime is taken from cloud store metadata mtime = parse_dropbox_date(metadata['modified']) ctime = headers.get('created', None) if ctime: ctime = datetime.fromtimestamp(parse_date(ctime)) id = page.lower() params = { "id" : id, "path" : page, "ctime" : ctime, "mtime" : mtime, "title" : headers.get('title', 'Untitled'), "tags" : headers.get('tags', None), "body" : body, "mime_type": mime_type, "headers" : headers } p = Page(**params) p.put() memcache.set(params['id'], params['headers'], namespace=NS_PAGE_METADATA) return p return None
def landing_page(self, file_id, content, slug): pages = Page.query().order(-Page.created_at).fetch() (title, tags, html) = parse_landing_page(content, pages) upsert_page( Page(file_id=file_id, slug=slug, title=title, tags=tags, content=html))
def create_page_post(context, request): data = request.POST page = Page(data['title']) page.layout_template = u'master.html' for behaviour in data.getall('behaviour'): page.update(behaviour, data, behaviour + '.') context[data['uid']] = page location = model_url(page, request) return HTTPFound(location = location)
def get_queryset(self): all_page_versions = Page(slug=self.kwargs['slug']).versions.all() # We set self.page to the most recent historical instance of the # page. if all_page_versions: self.page = all_page_versions[0] else: self.page = Page(slug=self.kwargs['slug'], name=self.kwargs['original_slug']) return all_page_versions
def setUp(self): self.scott = Account.new('scott', 'tiger', '*****@*****.**') self.scott_page = Page.new(self.scott, 'Book List') self.scott_rev = self.scott_page.save_draft_rev( 'book list sample text', True) self.scott_page.publish_draft_rev() self.sally = Account.new('sally', 'secret', '*****@*****.**') self.sally_page = Page.new(self.sally, 'Dear Diary') self.sally_rev = self.sally_page.save_draft_rev('today i am sad', True) self.sally_page.publish_draft_rev()
def view(self): route = self.request.matchdict['route'] page = Page.by_route(route) if page is None: return HTTPNotFound("No such page") return dict( page=page, pages=Page.all(), logged_in=authenticated_userid(self.request), )
def setup_database(app): with app.app_context(): db.create_all() home = Page() home.name = "Home" contact = Page() contact.name = Page() db.session.add(home) db.session.add(contact) db.session.commit()
def page_edit_about(request): shop = request.shop static_pages = Page.objects.filter(shop=shop) dynamic_pages = DynamicPageContent.objects.filter(shop=shop) try: about = About.objects.filter(shop=shop).get() except About.DoesNotExist: about = Page(shop=shop) about.save() if request.method == "POST": form = AboutForm(request.POST) if form.is_valid(): about.title = form.cleaned_data['title'] about.body = form.cleaned_data['body'] about.meta_content = form.cleaned_data['meta_content'] about.save() request.flash['message'] = unicode(_("Page successfully saved.")) request.flash['severity'] = "success" return HttpResponseRedirect(reverse('page_edit_about')) else: form = AboutForm(instance=about) return render_to_response('store_admin/web_store/pages_edit_about.html', { 'form': form, 'static_pages': static_pages, 'dynamic_pages': dynamic_pages }, RequestContext(request))
def create(): page = Page() form = PageForm(request.form, page) if form.validate_on_submit(): form.populate_obj(page) page.save() return redirect('/wiki/') return render_template('wiki_create.html', title="Wiki - create new page", page=page, form=form)
def add(): from db import pages for idx, pg in enumerate(pages.values()): #page = Page(id=pg['slug'], **pg) #page.idx = idx + 1 #page.put() Page.get_or_insert(pg['slug'], idx=idx + 1, body=open('html/{}.html'.format( pg['slug'])).read().decode('utf-8')**pg) return redirect('/about/')
def cut_results(self, user, key, results, num_results): saved_results = results[num_results:] results = results[:num_results] page = Page(retrieval_key = key) user.pages.append(page) for result in saved_results: page_item = PageItem(content = result) page_item.save() page.items.append(page_item) page.save() user.save() return (results, len(saved_results)> 0)
def save_page(request): if request.method == 'POST': print request.POST url = request.POST['url'] title = request.POST['title'] summary = request.POST['summary'] id = request.POST['id'] print id category = Category.objects.get(id=id) print category source = request.POST['source'] flesh_score = request.POST['flesh_score'] polarity = request.POST['polarity'] subjectivity = request.POST['subjectivity'] # Checks if we already have the same page in the category try: existent_page = Page.objects.filter(title=title, category=category) except: existent_page = None if not existent_page: page = Page(category=category, title=title, summary=summary, url=url, source=source, flesch_score=flesh_score, sentiment_score=polarity, subjectivity_score=subjectivity) # Saves it page.save() json_response = { "response": "Success", "category_id": category.id, 'category': category.slug } return JsonResponse(json_response) else: json_response = { "response": "Existent page", "category": category.slug, "category_id": category.id } return JsonResponse(json_response) else: # If the request was not a POST, display the form to enter details. return HttpResponseRedirect('/fhs/search/')
def test_edit_page(self): page = Page(title='test title', address='test_page', content='test content') db.session.add(page) assert self.is_only_for_admins('/edit/test_page/') self.login_as_admin() response = self.client.get('/edit/test_page/') assert response.status_code == 200 # title and content edit new_data = { 'address': 'changed_address', 'title': 'changed title', 'content': 'changed content' } self.client.post('/edit/test_page/', data=new_data, follow_redirects=True) assert page.address == new_data['address'] assert page.title == new_data['title'] assert page.content == new_data['content'] with self.assert_flashes('Address cannot be empty'): response = self.client.post( '/edit/changed_address/', data={ 'address': '', 'content': 'I accidentally removed address but want the content preserved!' }, follow_redirects=True) # user should get their edited text back (no one likes to loose his work) assert b'I accidentally removed address but want the content preserved!' in response.data # but the actual text should not be changed assert page.content == 'changed content' assert page.address == 'changed_address' # weird addresses for weird_address in self.weird_addresses: page = Page(address=weird_address) db.session.add(page) response = self.client.post('/edit/' + weird_address + '/', data={'title': 'new title'}) assert response.status_code == 200 assert page.title == 'new title' self.logout()
def post(self): file_id = self.request.get('file_id') page = Page.query_by_file_id(file_id).get() slug = page.slug content = get_file_content(self.service, file_id) if '0-landing-page' in slug: logging.debug('found landing page') self.landing_page(file_id, content, slug) elif not slug.startswith('0-'): self.blog_post(file_id, content, slug) else: # should match 0-tags-page upsert_page(Page(file_id=file_id, slug=slug, content=content))
def post(self, slug=None): if slug: page = Page.gql("WHERE slug = :1", slug).get() else: page = Page() page.title = self.request.get('title') page.slug = self.request.get('slug') page.content = self.request.get('content') page.order_in_menu = int(self.request.get('order_in_menu')) page.put() self.redirect(page.get_url())