Skip to content

Instantly share code, notes, and snippets.

@coleifer
Created Oct 30, 2011
Embed
What would you like to do?
Bookmark blueprint
import datetime
from flask import request, redirect, url_for, render_template, Blueprint
from peewee import *
from flaskext.rest import RestResource
from flaskext.utils import get_object_or_404, object_list
from app import app, db
from auth import auth
class Bookmark(db.Model):
url = TextField()
created_date = DateTimeField(default=datetime.datetime.now)
class Meta:
ordering = (('created_date', 'desc'),)
def __unicode__(self):
return self.url
bookmarks = Blueprint('bookmarks', __name__, template_folder='templates')
@bookmarks.route('/')
@auth.login_required
def list():
qr = Bookmark.select()
return object_list('bookmarks/index.html', qr)
@bookmarks.route('/add/')
@auth.login_required
def add():
url = request.args.get('url')
if url:
Bookmark.get_or_create(url=url)
return redirect(url or url_for('bookmarks.list'))
@bookmarks.route('/<pk>/delete/')
@auth.login_required
def delete(pk):
bookmark = get_object_or_404(Bookmark, id=pk)
bookmark.delete_instance()
return redirect(url_for('bookmarks.list'))
class BookmarkResource(RestResource):
pass
javascript:location.href='http://<your domain>.com/bookmarks/add/?url='+location.href;
{% extends "base.html" %}
{% block title %}Bookmarks{% endblock %}
{% block content_title %}Bookmarks{% endblock %}
{% block content %}
<ul>
{% for bookmark in object_list %}
<li><a href="{{ bookmark.url }}">{{ bookmark.url }}</a>
<a href="{{ url_for('bookmarks.delete', pk=bookmark.id) }}"><img src="{{ url_for('static', filename='img/delete.png') }}" /></a>
</li>
{% endfor %}
</ul>
{% include "includes/pagination.html" %}
{% endblock %}
<p class="pagination">
{% if page > 1 %}
<a class="previous" href="./?page={{ page - 1 }}">Previous</a>
{% endif %}
{% if pagination.get_pages() > page %}
<a class="next" href="./?page={{ page + 1 }}">Next</a>
{% endif %}
</p>
@plaes
Copy link

plaes commented Apr 12, 2012

You could use method based dispathing to show off advanced features of Flask and of course - to not use GET request to delete items which is currently an accident waiting to happen (just think what happens if search engine starts crawling your links).

@powersurge360
Copy link

powersurge360 commented May 5, 2012

Google wouldn't hit the delete because it's auth protected. Plus you'd have to introduce js if you want that url to work in a browser. IMO, it's fine as is.

Although class-based views are sick, and I hope anyone who reads this will check out the method based dispatching anyways :>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment