Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
duck monster
Dec 15, 2004

I'm trying to write a template filter that converts meters to feet (or not) DEPENDING on a preference flag in the users profile

so I can go {{ marina.maxdraught|metric }} and it'll convert it to meters or feet according to user prefs.

The problem is, I have no loving idea how to access the context in a @register.filter filter tag so I can get at the user and thus settings object. Is there some sort of request singleton I can magic into existance or SOMETHING that would let me get at this data?

Adbot
ADBOT LOVES YOU

Lamacq
Jun 15, 2001

Breezeblock RIP

duck monster posted:

I'm trying to write a template filter that converts meters to feet (or not) DEPENDING on a preference flag in the users profile

so I can go {{ marina.maxdraught|metric }} and it'll convert it to meters or feet according to user prefs.

The problem is, I have no loving idea how to access the context in a @register.filter filter tag so I can get at the user and thus settings object. Is there some sort of request singleton I can magic into existance or SOMETHING that would let me get at this data?

Can you modify your filter so that it accepts an argument (IE the request object)? So you'd write
code:
{{ marina.maxdraught|metric:request }}
And your filter code is basically
code:
@register.filter(name='metric')
def metric(value, request):
    # do stuff with request.user
    return 'foo'
I guess at that point you might as well write a full blown template tag, that's what I end up doing for stuff like this 99% of the time.

That said, I think the template filter/tag API is probably the thing I dislike most about Django. Don't get me wrong, I love the framework, but anytime I work outside it I vastly prefer Mako.

duck monster
Dec 15, 2004

It aint elegant, but it'll do I guess. This loving contracts a month overdue anyway so sperging on beautiful code is a bit redundant at this point.

And yeah, django is awesome when Im living inside its intended use, but as soon as I hit a scenario the authors didnt think of I swear I spend more time fighting the framework than being assisted by it.

Sometimes I actually miss the flexible stupidity of PHP+adodb+smarty. Now I must wash my brain in repentance for even thinking such sin.

duck monster fucked around with this message at 17:46 on Aug 11, 2011

raymond
Mar 20, 2004
You could use a template context processor to make this preference easily accessible in the template. Something like this:
code:
def user_preferences(request):
    use_metric = request.user.get_profile().use_metric
    return {'use_metric': use_metric, 'use_feet': not use_metric}
And make the filter take an argument like Lamacq said, but take the specific argument rather than the whole request.
code:
{{ marina.maxdraught|metric_if:use_metric }}
Or if a template tag is fine, perhaps make one with @register.simple_tag(takes_context=True)
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

German Joey
Dec 18, 2004
has anyone had any trouble applying Django fixtures with recursive relations? e.g. a user's profile refers to the last topic they created, and the topic refers to the user that created it, etc.

this was not a problem running the dev-server, on windows on my laptop, but my hosting on webfaction completely barfs with a really cryptic error:

code:
$ python2.5 manage.py loaddata testdump.yaml
/home/germanjoey/lib/python2.5/pygments/plugin.py:39: UserWarning: Module zinnia was already imported from /home/germanjoey/webapps/django/mysite/zinnia/__init__.pyc, but /home/germanjoey/lib/python2.5 is being added to sys.path
  import pkg_resources
/home/germanjoey/lib/python2.5/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_save method hasn't been updated to take a `connection` argument.
  new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
Problem installing fixture 'testdump.yaml': Traceback (most recent call last):
  File "/home/germanjoey/lib/python2.5/django/core/management/commands/loaddata.py", line 174, in handle
    obj.save(using=using)
  File "/home/germanjoey/lib/python2.5/django/core/serializers/base.py", line 165, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/home/germanjoey/lib/python2.5/django/db/models/base.py", line 570, in save_base
    created=(not record_exists), raw=raw, using=using)
  File "/home/germanjoey/lib/python2.5/django/dispatch/dispatcher.py", line 172, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/home/germanjoey/lib/python2.5/haystack/indexes.py", line 198, in update_object
    self.backend.update(self, [instance])
  File "/home/germanjoey/lib/python2.5/haystack/backends/whoosh_backend.py", line 174, in update
    writer.update_document(**doc)
  File "/home/germanjoey/lib/python2.5/whoosh/writing.py", line 407, in update_document
    self._record("update_document", args, kwargs)
  File "/home/germanjoey/lib/python2.5/whoosh/writing.py", line 384, in _record
    getattr(self.writer, method)(*args, **kwargs)
  File "/home/germanjoey/lib/python2.5/whoosh/writing.py", line 280, in update_document
    with self.searcher() as s:
  File "/home/germanjoey/lib/python2.5/whoosh/writing.py", line 100, in searcher
    return Searcher(self.reader(), **kwargs)
  File "/home/germanjoey/lib/python2.5/whoosh/filedb/filewriting.py", line 272, in reader
    self.generation, reuse=reuse)
  File "/home/germanjoey/lib/python2.5/whoosh/filedb/fileindex.py", line 330, in _reader
    readers = [segreader(segment) for segment in segments]
  File "/home/germanjoey/lib/python2.5/whoosh/filedb/fileindex.py", line 319, in segreader
    return SegmentReader(storage, schema, segment)
  File "/home/germanjoey/lib/python2.5/whoosh/filedb/filereading.py", line 71, in __init__
    self.storedfields = StoredFieldReader(sf)
  File "/home/germanjoey/lib/python2.5/whoosh/filedb/filetables.py", line 774, in __init__
    name_map = dbfile.read_pickle()
  File "/home/germanjoey/lib/python2.5/whoosh/filedb/structfile.py", line 220, in read_pickle
    return load_pickle(self.file)
UnpicklingError: unpickling stack underflow
needless to say, it took me many hours to even figure out what the problem was. It failed not only for my initial_data.json, but also direct XML and YAML (both of which supposedly support recursive relationships like this) datadumps of my dev-server's database loaded with the exact same fixture. both fail with the exact same unpickling stack underflow error. I've spent so much stupid time on this that I am close to screaming IRL!

as a temporary hack, I coded up a script that can split a .json file into separate .json's per-model, so that I can at least apply those that are not recursive. this is it, in case anyone else has a similar problem. this is the only way i was able to diagnose this bullshit at all:

code:
    #!perl
    use warnings;
    use strict;

    our $STRIP_WHITESPACE = 0;

    undef $/;
    # initial_data.json.bak = your raw, unsplit, formatted json file
    open(INPUT, "initial_data.json.bak") or die $!;
    my $input = <INPUT>;
    close INPUT;

    # nested parens... this assumes you don't have any '{' or '}' characters
    # in your records. what can i say, this is a hack. ;[
    my $nb;
    $nb = qr[\{
             (?:  (?> [^{}]+ )
                | (??{ $nb })
              )* \}
            ]x;

    my %models;
    while (1) {
        # extract record based on nested parens
        my($record) = $input =~ /($nb)/;
        last unless $record;
        
        # group by model
        my ($model) = $record =~ /"model": "(\w+(?:\.\w+)*)"/;

        push @{$models{$model}}, $record;
        my $qx_record = quotemeta($record);
        $input =~ s/$qx_record//;
    }

    while ( my ($k,$v) = each %models) {
        open(OUTPUT, ">", "$k.json") or die $!;
        print OUTPUT "[\n";
        for my $i (0..$#$v) {
            print OUTPUT $v->[$i];
            print OUTPUT ",\n" unless $i == $#$v;
        }
        print OUTPUT "\n]";
    }

    # strip whitespace, sometimes helps the parser? i dont know, what kind of
    # stupid parser chokes on whitespace between records...
    if ($STRIP_WHITESPACE) {
        undef $/;
        foreach my $k (keys %models) {
            open(INPUT, "$k.json") or die $!;
            my $input = <INPUT>;
            close INPUT;

            # strip out whitespace everywhere except inside strings; also, strip \r
            # and \n even inside strings because apparently these can be catastrophic
            # to the deserializing parser
            my $dqs = qr/" (?: [^\\"] | \\. )* "/x;
            $input =~ s/((?:[^\s"] | $dqs)+) \s+ /$1 /gx;
            $input =~ s/\r//g;
            $input =~ s/\n//g; 

            open(OUTPUT, ">", "$k.json") or die $!;
            print OUTPUT $input;
            close OUTPUT;

        }
    }
seriously this is an unbelievable pain, why can't this poo poo just work plain loving work...? does anyone have any ideas what I can do? is there any way to just load/unload raw sql from/to the database?

Yay
Aug 4, 2007

German Joey posted:

has anyone had any trouble applying Django fixtures with recursive relations? e.g. a user's profile refers to the last topic they created, and the topic refers to the user that created it, etc.
From a glance at the traceback, I'm guessing you're using Haystack with some RealTimeSearchIndexes? certainly the problem seems to be at the point which haystack would trigger an index update.

Disable haystack, and re-run, see if you get a better traceback?

Can't remember the last time I actually used fixtures, though, so YMMV.

German Joey
Dec 18, 2004

Yay posted:

From a glance at the traceback, I'm guessing you're using Haystack with some RealTimeSearchIndexes? certainly the problem seems to be at the point which haystack would trigger an index update.

Disable haystack, and re-run, see if you get a better traceback?

Can't remember the last time I actually used fixtures, though, so YMMV.

hmmm, i'll try that. your last comment makes me think I'm doing something obsolete, though. what do you do instead to initialize your DB full of data?

German Joey
Dec 18, 2004
ok, I *finally* got it, after so many hours. first, before I read your comment, I tried upgraded myself to python2.7, re-installing all 40 dependencies I have or whatever, but that didn't help. but then disabling haystack-search did seem to help!

I then got the error:
code:
$ python2.7 manage.py loaddata testdump.yaml
Problem installing fixture 'testdump.yaml': Traceback (most recent call last):
  File "/home/germanjoey/webapps/django/lib/python2.7/django/core/management/commands/loaddata.py", line 174, in handle
    obj.save(using=using)
  File "/home/germanjoey/webapps/django/lib/python2.7/django/core/serializers/base.py", line 165, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/home/germanjoey/webapps/django/lib/python2.7/django/db/models/base.py", line 570, in save_base
    created=(not record_exists), raw=raw, using=using)
  File "/home/germanjoey/webapps/django/lib/python2.7/django/dispatch/dispatcher.py", line 172, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/home/germanjoey/webapps/django/mysite/djangobb_forum/signals.py", line 19, in post_saved
    profile = post.user.forum_profile
  File "/home/germanjoey/webapps/django/lib/python2.7/django/db/models/fields/related.py", line 315, in __get__
    rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
  File "/home/germanjoey/webapps/django/lib/python2.7/django/db/models/query.py", line 350, in get
    % self.model._meta.object_name)
DoesNotExist: User matching query does not exist.
but like, what the hell does that mean? some googling showed that this error sometimes happens if you don't add an administrator during syncdb (as I didn't, as my fixture already has one). ok, so I do that, edit my fixture by hand to include a profile for the new extra admin, but then I still get the error. ok, so then I add some print statements to the modules in question, and I see that the real problem is that it can't find the User data for the old administrator. maybe this is because all the User data is at the end of the .yaml file because it is sorted alphabetically, I don't know. so anyways, I split that User into its own 1-index fixture, load that fine, and try my main fixture again and... it loads!... 3X as many indexes as it was supposed to, somehow. but at least it loads now!

arrgh, whatever, so I'm a Cerberus now! that's fine! I ain't spending another 5 hours debugging just to get my dummy data into the database!

edit: I just find now a bug-report relating this directly to haystack search's indexing:

https://github.com/toastdriven/django-haystack/issues/126

apparently, the indexes aren't stored in a database but in files which are tied to the structure of the database (or something like that), and I had uploaded them to the server. as I was now using a different database, it completely choked when it tried to update the indexes. rebuilding the indexes lets everything work just fine, i think... oh well!

German Joey fucked around with this message at 21:54 on Aug 11, 2011

Yay
Aug 4, 2007

German Joey posted:

ok, I *finally* got it, after so many hours. first, before I read your comment, I tried upgraded myself to python2.7, re-installing all 40 dependencies I have or whatever, but that didn't help. but then disabling haystack-search did seem to help!

arrgh, whatever, so I'm a Cerberus now! that's fine! I ain't spending another 5 hours debugging just to get my dummy data into the database!
1. I've never used fixtures that weren't JSON. Every time I've ever used fixtures, they've always been ordered by the PK. I don't know if that's some weird limitation of YAML.

2. Mostly, I don't want my database full of data. Mostly because it's client work, and beyond creating say, administrators, or basic content set up, it's entirely up to them to put stuffs in. On the occassions when I do, I run actual honest-to-goodness SQL dumps (and if I'm feeling really goddamn lazy, just copy the database from one of the test connections to the production ones via SQLYog tunnels.)

3. Looking at your new traceback, I think your problem there is signals being fired post_save, expecting a user and/or profile, and don't do so gracefully in the face of an error, by the look of it.

4. If you do use fixtures, split them out into distinct parts where possible, precisely so you can run them in an order. Also, never, ever call them initial_data, despite what the Django docs say. The moment you add a new app and think to syncdb* the live server, you'll be punching yourself for overwriting existing data.

* This assumes the app you're adding is loving stupid, and doesn't provide South migrations.

Lobe
Jul 27, 2009
I loving hate Django's ORM, it is really not that great compared to SqlAlchemy, lacking really really basic stuff like indexes on multiple fields and bulk inserts (yes, really). I really like the MVC stuff though, but I also detest the settings (its a real pain to deploy, the absolute paths are a nightmare).

Can anyone else relate?

epswing
Nov 4, 2003

Soiled Meat
Re: deployment, it's a one time thing...after I get my deployment script working, I forget about it, and I haven't had to think about it since. How are absolute paths nightmares?

epswing fucked around with this message at 01:02 on Aug 12, 2011

Hughlander
May 11, 2005

Lobe posted:

I loving hate Django's ORM, it is really not that great compared to SqlAlchemy, lacking really really basic stuff like indexes on multiple fields and bulk inserts (yes, really). I really like the MVC stuff though, but I also detest the settings (its a real pain to deploy, the absolute paths are a nightmare).

Can anyone else relate?

Top of settings.py:
code:
ROOT_PATH = abspath(dirname(__file__))
rest of settings.py:
code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': join(ROOT_PATH, 'db', 'thedb.db'),# Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}
No more absolute paths.

Yay
Aug 4, 2007
Honestly, my biggest gripes with Django are settings related.

1. As Hughlander points out, providing a setting for the root path is a sensible default for 80% of users, easily. Things like django CMS even include it as part of their tutorial, because it makes everything easier. For the 20% of cases when its not appropriate (usually because your settings file is not the default), then it's easy to override.

2. I wish there were a sanctioned recommendation for how to have settings set up, because your local settings and deployment settings are never the same. They just aren't. And I know it's a hard problem (despite it seeming obvious at first glance, that glance is inevitably skewed to your situation) to solve, but that's the kind of thing Django is supposed to solve. It's a far more relevant problem than contrib.comments and contrib.redirects, say.

As it is, everyone has half-baked setups for settings, and no two are alike.

SelfOM
Jun 15, 2010
I've been getting this error after I changed over to PostgreSql: "Caught DatabaseError while rendering: relation 'model_Foreignkey' not found."

The model has two fields, one of which is Foreign Key the other which is a m2m, both to users. I've got the related names set for both of the relations. Doesn't look like south or manage.py sqlreset is generating both the relation tables. This works fine on sqlite3, when I run syncdb. I was using South, and I thought that might of been the problem, so turned it off and tried again. Unfortunately that doesn't seem to be it.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Yay posted:

Honestly, my biggest gripes with Django are settings related.

1. As Hughlander points out, providing a setting for the root path is a sensible default for 80% of users, easily. Things like django CMS even include it as part of their tutorial, because it makes everything easier. For the 20% of cases when its not appropriate (usually because your settings file is not the default), then it's easy to override.

2. I wish there were a sanctioned recommendation for how to have settings set up, because your local settings and deployment settings are never the same. They just aren't. And I know it's a hard problem (despite it seeming obvious at first glance, that glance is inevitably skewed to your situation) to solve, but that's the kind of thing Django is supposed to solve. It's a far more relevant problem than contrib.comments and contrib.redirects, say.

As it is, everyone has half-baked setups for settings, and no two are alike.

I normally just use settings as a module. That lets me do per instance settings based upon whatever I want, hostname, env variables, whatever and keeps things nice and orderly too.

Hughlander
May 11, 2005

Profane Obituary! posted:

I normally just use settings as a module. That lets me do per instance settings based upon whatever I want, hostname, env variables, whatever and keeps things nice and orderly too.

Right but everyone's way of doing the 'based upon whatever I want' is done differently. If I was to sit down with your settings I'd have to learn how you do it, if you were to sit down with mine, you'd have to learn mine. There's a million ways to do it, none standard, which is very unpythonistic.

For example, now I base everything off of basedir and try to keep the settings the same as much as possible because I like to do just spin up a new virtualenv, do a pip install -r requirements.txt and go.

Previously, I had something like this at the end of my settings.conf:
code:

import glob
import socket

startswith = os.environ['DJANGO_SETTINGS_MODULE'].split('.')[0]
for app in INSTALLED_APPS:
    if app.startswith(startswith):
        app = app.split('.')[-1]
        conffiles = glob.glob(os.path.join(os.path.dirname(__file__), app, 'settings', '*.conf'))

        conffiles.sort()
        for f in conffiles:
            try:
                execfile(os.path.abspath(f))
            except ImportError, e:
                raise e

        hostname = socket.gethostname().replace('.','_')
        fileglob = '*%s.conf' % hostname
        conffiles = glob.glob(os.path.join(os.path.dirname(__file__), app, 'settings', 'perhost', fileglob))
        for f in conffiles:
            try:
                execfile(os.path.abspath(f))
            except ImportError, e:
                raise e
It'd do per machine based .conf file and use a numeric order to override them:
(10-devhost.conf comes before 15-devhost.conf)

Now if you want to handle QA and staging on the same machine but in different directories you'd have to come up with a 3rd way then what I've done.

Yay
Aug 4, 2007
As a further example of disparate settings; at work we've iterated through per-host settings:

1. normal settings module.
2. settings does a hostname lookup, like hughlander, and includes host specific conf as an override for previously defined settings.

and we currently have:
1. default settings in ... settings_default
2. settings_machine on the pythonpath for the env or server; this imports * from settings_default
3. settings, which imports from settings_machine (so that we don't have to provide the settings module explicitly)

Neither satisfies me, and nor do any of the re-usable apps I've seen (although y'know, they all work). Like I said, it's a hard problem to get right. Especially when some people want secret keys/db passwords etc able to be version controlled, and some don't.

German Joey
Dec 18, 2004
Is there a way to use signals to prevent an object from being saved? Specifically, I'm trying to add "ignore list" functionality to django messages, and I had just typed up:

code:

from messages.models import Message

def message_ignorelist_check(instance, **kwargs):
    if kwargs.get('raw', False) is False:
        if kwargs.get('created', False) is True:
            message = instance
            to = message.sender
            from = message.recipient
            
            if (from in to.profile.ignore_list.all()) or (to in from.profile.ignore_list.all()):
                ...
                
pre_save.connect(message_ignorelist_check, sender=Message)
When I realized that I didn't have a clue on how to ground the signal! (the "..." line in the code) Is there an easy way to do this? returning False maybe, or perhaps some attribute to set on the instance? the docs are turning up blank. =[

Yay
Aug 4, 2007
I don't see why you're using a signal there when you could just override save() on message? You could really just avoid calling the parent save method if it doesn't meet your criteria (ie: someone is ignoring someone else)

Signals are for doing things, mostly to other objects, at certain points (Say, you might want to send an EmailMessage or whatever when someone updates a ticket) that wouldn't be appropriate to tie to the model. I realise that's a poor explanation, but it's the best I can do at this time of night.

(To further answer your question, I honestly don't understand the docs, and cannot tell if the success or failure of a signal can halt the other machinery)

German Joey
Dec 18, 2004

Yay posted:

I don't see why you're using a signal there when you could just override save() on message? You could really just avoid calling the parent save method if it doesn't meet your criteria (ie: someone is ignoring someone else)

Signals are for doing things, mostly to other objects, at certain points (Say, you might want to send an EmailMessage or whatever when someone updates a ticket) that wouldn't be appropriate to tie to the model. I realise that's a poor explanation, but it's the best I can do at this time of night.

(To further answer your question, I honestly don't understand the docs, and cannot tell if the success or failure of a signal can halt the other machinery)

Yeah, I couldn't understand them either, lol. Django documentation is pretty good for normal stuff but not so great if you have to do anything weird. I was hoping to use a signal here because my interaction with the "messages" app currently isn't much more than having added a line, "messages", in my installed apps, a similar line in my urls.py, and adding a link in my menu template to a user's inbox.

Oh well. I've been using them successfully in situations similar to what you describe, but I guess I'm gonna have to do something KRaZee and uGlY to the poor, lil innocent save method of that model...

Ferg
May 6, 2007

Lipstick Apathy
What's everybody's pick for a full-service host? I'm looking for something like App Engine, where all of the hosting dirty work is in the price. Our team isn't big enough to handle server maintenance so we'd like to just hand it off to the hosting provider to worry about scaling and uptime. Obviously the host would need to run Django, preferably MySQL.

That being said, how is django-nonrel these days? Last I checked it was full featured but had some gaping holes, like no support for many-to-many fields, but I can't find that limitation listed anymore on the site so maybe it's fixed.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I really liked WebFaction the last time I had to use Django. At the time they were just rolling out some new sever scaling features but it looked promising. I know they offer MySQL databases, but I'm not sure what else.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Ferg posted:

What's everybody's pick for a full-service host? I'm looking for something like App Engine, where all of the hosting dirty work is in the price. Our team isn't big enough to handle server maintenance so we'd like to just hand it off to the hosting provider to worry about scaling and uptime. Obviously the host would need to run Django, preferably MySQL.

Ep.io and Gondor are both pretty awesome.

IsotopeOrange
Jan 28, 2003

Ferg posted:

What's everybody's pick for a full-service host? I'm looking for something like App Engine, where all of the hosting dirty work is in the price. Our team isn't big enough to handle server maintenance so we'd like to just hand it off to the hosting provider to worry about scaling and uptime. Obviously the host would need to run Django, preferably MySQL.

That being said, how is django-nonrel these days? Last I checked it was full featured but had some gaping holes, like no support for many-to-many fields, but I can't find that limitation listed anymore on the site so maybe it's fixed.

I've been using nonrel with App Engine for my latest project and it's going really well so far. Many-to-many still isn't supported, model inheritance is fairly specific, and there are some other restrictions such as no SSL. It can be frustrating to work around the service but I think it'll be worth it in the end to not worry about scaling the infrastructure. You can find the limitations here

jarito
Aug 26, 2003

Biscuit Hider
Just getting started with a project at work in Django. The app is a pure ReST interface (no web front end). I've noticed there are some plugins for making ReSTful Django interfaces, but the basic Django handlers and stuff seem like they would work fine.

For a pure ReST interface app, should I use a library / plugin? Or just use the basic handlers from Django?

Mulozon Empuri
Jan 23, 2006

jarito posted:

Just getting started with a project at work in Django. The app is a pure ReST interface (no web front end). I've noticed there are some plugins for making ReSTful Django interfaces, but the basic Django handlers and stuff seem like they would work fine.

For a pure ReST interface app, should I use a library / plugin? Or just use the basic handlers from Django?

I've had good luck with using django-tastypie for my apis.

Ferg
May 6, 2007

Lipstick Apathy

jarito posted:

Just getting started with a project at work in Django. The app is a pure ReST interface (no web front end). I've noticed there are some plugins for making ReSTful Django interfaces, but the basic Django handlers and stuff seem like they would work fine.

For a pure ReST interface app, should I use a library / plugin? Or just use the basic handlers from Django?

Tastypie is good, though I find it hard to tear myself away from Piston. Just make sure you're using Mozilla's fork (on Github) since the original Piston project has been abandoned.

Ferg
May 6, 2007

Lipstick Apathy

MonkeyMaker posted:

Ep.io and Gondor are both pretty awesome.

MEAT TREAT posted:

I really liked WebFaction the last time I had to use Django. At the time they were just rolling out some new sever scaling features but it looked promising. I know they offer MySQL databases, but I'm not sure what else.

Ep.io and Gondor look pretty good, but being that they're invite-only and I'm looking to make a transition for a client within the next week I don't think they're viable yet. WebFaction is definitely appealing due to full SSH access since this particular site also leverages a Redis database for one component. How about DotCloud? I was using Duostack for a node.js project a while back and they were pretty good, but got eaten up by these guys.

Mulozon Empuri
Jan 23, 2006

Ferg posted:

Tastypie is good, though I find it hard to tear myself away from Piston. Just make sure you're using Mozilla's fork (on Github) since the original Piston project has been abandoned.

I donno, the last time I tried piston it returned status codes in plain text, form errors as html and didn't have pagination.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Ferg posted:

Ep.io and Gondor look pretty good, but being that they're invite-only and I'm looking to make a transition for a client within the next week I don't think they're viable yet. WebFaction is definitely appealing due to full SSH access since this particular site also leverages a Redis database for one component. How about DotCloud? I was using Duostack for a node.js project a while back and they were pretty good, but got eaten up by these guys.

Do you need an Invite to Gondor? I should be able to get you one. Gondor is being used in production, the billing is just not automatic yet so it's still invite only beta (with beta accounts being free, but the accounts with more resources being billed manually)

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
I tried to use django-piston a few times, and almost always ended up getting frustrated and just did it myself manually. Tastypie is great and makes building a an api quick and painless.

Shameless plug: If you want to consume a Tastypie API: http://slumber.in/ is awesome for it

Mulozon Empuri
Jan 23, 2006

Profane Obituary! posted:

Shameless plug: If you want to consume a Tastypie API: http://slumber.in/ is awesome for it

Hmm, that looks pretty handy. Thanks for the tip.

No Safe Word
Feb 26, 2005

jarito posted:

Just getting started with a project at work in Django. The app is a pure ReST interface (no web front end). I've noticed there are some plugins for making ReSTful Django interfaces, but the basic Django handlers and stuff seem like they would work fine.

For a pure ReST interface app, should I use a library / plugin? Or just use the basic handlers from Django?

Just so you don't get confused later on, ReST is for ReStructured Text, whereas REST is never abbreviated like that, it's pretty much always all caps.

Lamacq
Jun 15, 2001

Breezeblock RIP

Profane Obituary! posted:

I tried to use django-piston a few times, and almost always ended up getting frustrated and just did it myself manually. Tastypie is great and makes building a an api quick and painless.

Shameless plug: If you want to consume a Tastypie API: http://slumber.in/ is awesome for it

Ooh thank you, I may just have a need for this soon. I'm working with a dude who is building this whole backend infrastructure in .NET that I will be writing a web frontend for, and I really don't want to have to build it in ASP.NET (even ASP.NET MVC looks pretty janky to me) so I wrote RESTful WCF services for it, so I can still build the frontend in Django and just communicate with the backend via some nice RESTful HTTP requests. I was going to build that bit by hand but this looks like it may save me some work. Thanks!

VVVVVVV Wow that's pretty impressive, thanks for the link

Lamacq fucked around with this message at 16:13 on Aug 24, 2011

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?
I'm using this and like it: http://django-rest-framework.org/

Lamacq
Jun 15, 2001

Breezeblock RIP
Hey Mr. Obituary: I'm assuming you're the author of Slumber? Does it only work with services that offer a Tastypie-style self-describing API? That is, if I want to use it, do I have to create /api/v1/ and /api/v1/<resource>/schema/ documents that match what tastypie would output, in order for slumber to know what to do?

Ferg
May 6, 2007

Lipstick Apathy

Profane Obituary! posted:

I tried to use django-piston a few times, and almost always ended up getting frustrated and just did it myself manually. Tastypie is great and makes building a an api quick and painless.

Shameless plug: If you want to consume a Tastypie API: http://slumber.in/ is awesome for it

I don't disagree at all, it has some glaring issues. Typically though the APIs I'm building aren't public facing though, so we can work around the lovely parts. The implementation side really is nice, and that's what I have a hard time giving up.

Profane Obituary! posted:

Do you need an Invite to Gondor? I should be able to get you one. Gondor is being used in production, the billing is just not automatic yet so it's still invite only beta (with beta accounts being free, but the accounts with more resources being billed manually)

Does it allow use of more than one database for an app? Their site isn't terribly descriptive. I would need both MySQL and Redis for the project I'll be deploying in the coming weeks.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Lamacq posted:

Hey Mr. Obituary: I'm assuming you're the author of Slumber? Does it only work with services that offer a Tastypie-style self-describing API? That is, if I want to use it, do I have to create /api/v1/ and /api/v1/<resource>/schema/ documents that match what tastypie would output, in order for slumber to know what to do?

Yea I am the author. It's actually much simpler then that. It doesn't use the /schema/ url at all. It just makes some assumptions about how urls are structured and HTTP Verbs.

Basically when you create an api object that lives at say http://slumber.in/api/v1/, and when you do api.resource_name.get(), it just basically does GET http://slumber.in/api/v1/resource_name/ same with POST, PUT, DELETE. If you do api.resource_name(some_id_value).get(), it does GET http://slumber.in/api/v1/resource_name/some_id_value/ etc.

It's basically just a wrapper to automatically infer the url, url paramters, (and the body of the request for POST/PUT) and automatically handle making the request for you.

I mean to add support for nested resources but currently it is not supported.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Ferg posted:


Does it allow use of more than one database for an app? Their site isn't terribly descriptive. I would need both MySQL and Redis for the project I'll be deploying in the coming weeks.

MySQL isn't supported (Can you use PostgreSQL?)

Redis is supported.

Each Instance of a Site get's 1 PostgreSQL DB (with PostGIS If I do recall), can optionally get a redis instance in addition to the postgresql db.

Instances are just basically copies of your site living at a particular url, so you might end up with one for production, one for staging, and multiple for dev, or whatever work flow you need.

Adbot
ADBOT LOVES YOU

MonkeyMaker
May 22, 2006

What's your poison, sir?
Just ask for @epdotio or @gondor invites on Twitter. They'll respond pretty quickly.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply