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.
 
  • Locked thread
Vivian Darkbloom
Jul 14, 2004


I've been hacking away at a little game project in Python, and I stumbled across this problem. I know the solution is probably something trivial but I can't track it down and I'm increasingly bugged.

My question: I have a method that takes a class as an argument. How do I tell the method to make a new object of that class? I guess you could use __new__ but that seems odd.

Adbot
ADBOT LOVES YOU

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

LochNessMonster posted:

I can imagine it's difficult to understand as you can't see the html source I'm trying to parse. I (now) understand the general idea you were showing me and I think I found a way to make that work, so thanks for that!

Aww yea

You should definitely read up on classes and stuff, just so you're aware of the general idea (even if you don't end up using them). It's good to be aware of this general idea of being able to drop in different objects and use them in some consistent way, so you can separate the specifics and reuse the general bit
https://learnpythonthehardway.org/book/ex40.html
that looks decent


Hughmoris posted:

My python skills (and programming in general) are pretty amateur so I'm walking through each solution and trying to understand how it works. Thanks for taking the time to write these up, and I'll let you know how it turns out.

Oh I'd have commented it more if I'd known - if you want to know anything, just ask!
Eela6's solution and mine are basically the same, we're just constructing the data a bit differently. Mine basically goes like this (it's like a pipeline)
Python code:
# these two lines handle opening a file as a CSV, and creating a 'DictReader' object
# that reads each line on demand and turns it into a record dictionary
with open('icu.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    # this gets all the dictionaries, but ditches the ones that don't mention the ICU (no need to process them)
    icu_transfers = (t for t in reader if t[FROM] == ICU or t[TO] == ICU)
    # this just takes each record dict and replaces its DATE_TIME string with an actual datetime object
    timestamped_transfers = (convert_timestamp(t) for t in icu_transfers)
    # now you can sort on the datetimes
    # e.g. sorted(timestamped_transfers, key=lambda x:x[TIME])

    # this gets each return transfer to the ICU (i.e. only where the patient previously transferred OUT of it)
    # it's a pair of both transfers, so you have both bits of info, with keys 'left' and 'returned'
    returns = get_icu_returns(timestamped_transfers)
    # this defines a filter, since you only care about the transfer pairs where the return is within 24 hours
    under_24_hrs = lambda r : r['returned'][TIME] - r['left'][TIME] <= timedelta(hours=24)
    # this runs the filter and makes a list of the results
    quick_returns = list(filter(under_24_hrs, returns))
I'm using generator comprehensions (like (convert_timestamp(t) for t in icu_transfers), in parentheses) which work like list comprehensions, except they don't produce a list - they just spit out each item when something asks for one. So you're not actually building a data structure in memory to hold everything, which can be important if you're reading in gigabytes of data - it's better to work on one thing at a time, or at least filter out all the stuff you don't need before you start building a list or whatever.

The way I wrote mine, it just reads one record at a time, and passes it right through to the end (maybe storing it in the dictionary that remembers the last time a patient left the ICU). It's only the last line that finally builds a list - but you could just write those results to a file instead, one thing at a time. If your CSV data isn't sorted though, you need to collect it into a list so you can sort it all, so that's why the sorted(timestamped_transfers, key=lambda x:x[TIME]) line is there (that spits out a list, so you need to assign the result to a variable and make the next line run on that). It happens after you've filtered out the records you don't care about though, so it at least cuts things down

You might not care about any of that, and if it's a small dataset then it probably won't matter anyway, but I'm into it! I think it's this guy's fault
http://www.dabeaz.com/generators-uk/
The pdf of the slides is really readable on its own

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Vivian Darkbloom posted:

I've been hacking away at a little game project in Python, and I stumbled across this problem. I know the solution is probably something trivial but I can't track it down and I'm increasingly bugged.

My question: I have a method that takes a class as an argument. How do I tell the method to make a new object of that class? I guess you could use __new__ but that seems odd.

From looking around, this is possible but it's pretty hacky, which makes it seem like you're not really meant to do this kind of thing. What exactly are you doing? If you lay out the general plan then people might have some more, uh, pythonic suggestions

Space Kablooey
May 6, 2009


Vivian Darkbloom posted:

I've been hacking away at a little game project in Python, and I stumbled across this problem. I know the solution is probably something trivial but I can't track it down and I'm increasingly bugged.

My question: I have a method that takes a class as an argument. How do I tell the method to make a new object of that class? I guess you could use __new__ but that seems odd.

Just call the class.

Python code:
def instance_new_object(whatever):
  return whatever()


class Butt():
  pass

butt = instance_new_object(Butt)

Space Kablooey fucked around with this message at 17:55 on Oct 7, 2016

chutwig
May 28, 2001

BURLAP SATCHEL OF CRACKERJACKS

baka kaba posted:

From looking around, this is possible but it's pretty hacky, which makes it seem like you're not really meant to do this kind of thing. What exactly are you doing? If you lay out the general plan then people might have some more, uh, pythonic suggestions

It's not hacky, it's just taking advantage of first-class objects, and you'd treat it as any other callable.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

chutwig posted:

It's not hacky, it's just taking advantage of first-class objects, and you'd treat it as any other callable.

Oh is it that easy? All the SO answers had a billion variations on One Weird Reflection Trick. That's cool then :frogbon:

QuarkJets
Sep 8, 2008

Yeah it turns out that SO is actually pretty terrible most of the time

e: With the section of this post, although technically it's the mathematica domain:
http://mathematica.stackexchange.com/questions/66538/how-do-i-draw-a-pair-of-buttocks

Vivian Darkbloom
Jul 14, 2004


subway masturbator posted:

Just call the class.

Python code:
def instance_new_object(whatever):
  return whatever()


class Butt():
  pass

butt = instance_new_object(Butt)

Perfect, I knew it had to be something sensible like this.


baka kaba posted:

From looking around, this is possible but it's pretty hacky, which makes it seem like you're not really meant to do this kind of thing. What exactly are you doing? If you lay out the general plan then people might have some more, uh, pythonic suggestions

Honestly I don't even have a special use case that demands this, I just got curious. What I'm doing (and I recognize I may not be doing it in the most efficient manner) is that I had dictionaries of the different units that players are allowed to deploy. The dictionary for a player has keys for each unit class and values for how many the player is allowed to field. Then when the player picks unit X to deploy, the placement method looks it up by class.

Man, that was a complicated way to implement this.

Eela6
May 25, 2007
Shredded Hen
Subway masturbator is 100% correct. To further expand on his point, you can also handle positional and keyword arguments with *args and **kwargs!

I made a small example for a strategy game below.
EG:
Python code:
class Unit:
     def __init__(self):
          pass
     

class Footman(Unit):
     def __init__(self, currentHp = 5, power = 5, maxHp = 5):
          self.currentHp = currentHp
          self.maxHp = maxHp
          self.power = power
          self.attackRange = 1
          self.armor = 2

     def __repr__(self):
          return 'Footman(currentHp = {0}, power = {1}, maxHp = {2})'.format(
                          self.currentHp, self.power, self.maxHp)

     def takeDamage(self, damage):
          self.currentHp -= max(damage-self.armor, 0)

def makeUnit(unitType, *args, **kwargs):
     return unitType(*args, **kwargs)

steve = makeUnit(Footman)
superSteve = makeUnit(Footman, 50, 100, maxHp = 250)
print(repr(steve))
steve.takeDamage(4)
print(repr(steve))
print(repr(superSteve))
-- >
code:
Footman(currentHp = 5, power = 5, maxHp = 5)
Footman(currentHp = 3, power = 5, maxHp = 5)
Footman(currentHp = 50, power = 100, maxHp = 250)
For anyone who wants to expand their python knowledge, I highly recommend 'Fluent Python' by Luciano Ramalho, it taught me nearly all my tricks.

Eela6 fucked around with this message at 20:55 on Oct 7, 2016

FoiledAgain
May 6, 2007

I'm trying to understand Enums in Python 3.5 and I can't get the __init__ method to work. I'm trying to base my stuff off the "Planets" example in the official docs. However, I get an AttributeError (shown below). Any suggestions?

code:
from enum import Enum

class Fingers(Enum):
    thumb = (1, 'thumb')
    index = (2, 'index')
    middle = (3, 'middle')
    ring = (4, 'ring')
    pinky = (5, 'pinky')
    
    def __init__(self,num,name):
        self.num = num
        self.name = name

print([x for x in Fingers])


Traceback (most recent call last):
  File "C:/Python35/enum_example.py", line 3, in <module>
    class Fingers(Enum):
  File "C:\Python35\lib\enum.py", line 158, in __new__
    enum_member.__init__(*args)
  File "C:/Python35/enum_example.py", line 12, in __init__
    self.name = name
  File "C:\Python35\lib\types.py", line 136, in __set__
    raise AttributeError("can't set attribute")
AttributeError: can't set attribute

Eela6
May 25, 2007
Shredded Hen
In enums, self.name is reserved -that's the name you chose, i.e, 'thumb'. You don't need to specify it because you get it 'for free' as part of an Enum. Check it out!

Python code:

from enum import Enum
from enum import Enum

class Fingers(Enum):
    thumb = 1
    index = 2
    middle = 3
    ring = 4
    pinky = 5
    
    def __init__(self,num):
        self.num = num

print([x for x in Fingers])

for finger in Fingers:
     print(finger.name)
Results
code:
[<Fingers.thumb: 1>, <Fingers.index: 2>, <Fingers.middle: 3>, <Fingers.ring: 4>, <Fingers.pinky: 5>]
thumb
index
middle
ring
pinky

FoiledAgain
May 6, 2007

Eela6 posted:

In enums, self.name is reserved -that's the name you chose, i.e, 'thumb'. You don't need to specify it because you get it 'for free' as part of an Enum. Check it out!

Well I feel a little silly for making that mistake. Thank you so much!

Dominoes
Sep 20, 2007

Would it be possible to write a Pycharm plugin to support unicode (ie greek letter) shortcuts like in Ipython/jupyter/julia ? ie type '\gamma tab' to get the letter. If this is doable, I might try.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

If you just need a small number of them it'd be easier to just use live templates.

Dominoes
Sep 20, 2007

That works; didn't know about the feature. Defining a live template for each greek char under settings, then setting its applicability to Python (or all, etc) works; hit ctrl+j, 'pi', tab. This is p much the same as ipython, but with ctrl+j instead of \.

Edit: even simpler syntax: 'Delta', tab.... or 'Del' tab. Solved.

It looks like you can save this as XML files under your phycharm directory/config/templates. Ie Greek letters.xml:

XML code:
<templateSet group="Greek letters">
  <template name="tau" value="&#964;" description="" toReformat="false" toShortenFQNames="true">
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
  <template name="Omega" value="&#937;" toReformat="false" toShortenFQNames="true">
    <context>
      <option name="Python" value="true" />
    </context>
  </template>
...

Dominoes fucked around with this message at 16:51 on Oct 8, 2016

Eela6
May 25, 2007
Shredded Hen
As tempting as it is to use identifiers in Linear A , it's widely considered non-pythonic.

Dominoes
Sep 20, 2007

That's an SA forums artifact.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

That works; didn't know about the feature.

It's great. I've got a couple dozen of them set up besides the one PyCharm comes with and I use them extensively to generate a ton of code by just typing a couple characters and pressing Tab.

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

Dominoes posted:

Would it be possible to write a Pycharm plugin to support unicode (ie greek letter) shortcuts like in Ipython/jupyter/julia ? ie type '\gamma tab' to get the letter. If this is doable, I might try.

If this isn't an explicit piece of functionality already it's definitely possible with snippets. I'm sure I've done this in a JetBrains editor.

Edit: oops there were more posts

sd6
Jan 14, 2008

This has all been posted before, and it will all be posted again
I'm having some issues upgrading a package in python. I tried to upgrade the python cassandra-driver package from version 3.6 to 3.7 using pip, but when I try to use the newly installed package with my desired python version of choice, I get an error:
code:
ImportError: ../site-packages/cassandra/cluster.so: undefined symbol: PyUnicodeUC32_DecodeUTF8
According to https://docs.python.org/2/faq/extending.html#when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2, my preferred Python install is using 4 bytes for unicode characters, and the new cassandra driver install is built with a python that uses 2 byte representations. So my question is, how do I get pip to install and build this package with the "correct" Python version for 4 byte unicode?


EDIT: So I noticed a warning message with my pip install about not being able to use a pip cache in my home directory while running install commands with sudo. I uninstalled the package, then re-installed with the '-H' flag for sudo and it seems to have worked this time. Not sure if something in pip cache was screwed up and was somehow telling pip to install a version with the wrong unicode width, but in any case it seems to be fixed now :)

sd6 fucked around with this message at 16:47 on Oct 11, 2016

Vivian Darkbloom
Jul 14, 2004


I would like to display color, bold, etc. output to the terminal. Apparently Colorama is a good library for making sure color codes display right on any OS. That author recommends either Blessings or Termcolor as a way to actually generate the color codes and such, any recommendations on that front?

I tried to get Blessings working but when I import it I get: "NameError: name 'unicode' is not defined" when it tries to subclass 'unicode' (I am guessing this is a Python 2 to 3 issue).

e: 3 minutes later, this looks good -- https://pypi.python.org/pypi/blessed/1.8.5

Vivian Darkbloom fucked around with this message at 05:58 on Oct 12, 2016

LochNessMonster
Feb 3, 2005

I need about three fitty


Another (likely dumb) question about something I don't quite understand.

I figured I'd take the following route with parsing different variations of a specific webstore template. Each dealer has a specific variation of div/span classes in which the price, milage and year info is stored. Since there are only a few options per value I'd like to scrape, I figured I'd write a loop that checks which dealer uses which variation. I store which dealersite uses which variation in dictionary with the dealername as key, and the values in a tuple.

Python code:
dealerInfo = {"alpha": "(2, 1, 2)",
	      		"bravo": "(3, 2, 3)",
	      		"charlie": "(2, 1, 2)",
	      		"delta": "(2, 1, 1)",
			}
Later on I base which beautifulsoup search should be done on the flags in this dict.

Python code:
for dealerName, flags in dealerInfo.items():

<some code>

#getPrice dependant on flag[1]
                if flags[1] == "1":
                    getPrice = vehicle.find("span", {"class": "price"})
                elif flags[1] == "2":
                    getPriceDiv = vehicle.find("div", {"class": "vehicleSpecs"})
                    getPrice = getPriceDiv.find("span", {"class": "price"})
                elif flags[1] == "3":
                    getPriceDiv = vehicle.find("div", {"class": "vehiclePrices"})
                    getPrice = getPriceDiv.find("span", {"class": "price"})
                elif flags[1] == "4":
                    getPriceDiv = vehicle.find("div", {"class": "vehiclePrice"})
                    getPrice = getPriceDiv.find("span", {"class": "price"})
This works perfectly fine , but I figured the values in the dictionary would be flag[0], flag[1] and flag[2]. That however does not return the values I'd like. It returns: "(", "2" and "," respectively. So it seems the value of the dictionary is being treated as a string instead of a tuple. Which works, as long as I take the correct position of the string, but it's not what I had in mind.

fake edit: while I'm typing this I'm realizing my error. If I don't wrap the tuple in quotes, and remove the quotes from the if flags[x] == "value" it treats the tuple as a tuple instead of a string...

:ughh:

psydude
Apr 1, 2008

Is the python plugin for Eclipse or NetBeans any good?

QuarkJets
Sep 8, 2008

psydude posted:

Is the python plugin for Eclipse or NetBeans any good?

I've heard that the Eclipse python plugin is good. But I don't personally use it, as a PyCharm / vim user

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

LochNessMonster posted:

Another (likely dumb) question about something I don't quite understand.

I figured I'd take the following route with parsing different variations of a specific webstore template. Each dealer has a specific variation of div/span classes in which the price, milage and year info is stored. Since there are only a few options per value I'd like to scrape, I figured I'd write a loop that checks which dealer uses which variation. I store which dealersite uses which variation in dictionary with the dealername as key, and the values in a tuple.

Python code:
dealerInfo = {"alpha": "(2, 1, 2)",
	      		"bravo": "(3, 2, 3)",
	      		"charlie": "(2, 1, 2)",
	      		"delta": "(2, 1, 1)",
			}
Later on I base which beautifulsoup search should be done on the flags in this dict.

Python code:
for dealerName, flags in dealerInfo.items():

<some code>

#getPrice dependant on flag[1]
                if flags[1] == "1":
                    getPrice = vehicle.find("span", {"class": "price"})
                elif flags[1] == "2":
                    getPriceDiv = vehicle.find("div", {"class": "vehicleSpecs"})
                    getPrice = getPriceDiv.find("span", {"class": "price"})
                elif flags[1] == "3":
                    getPriceDiv = vehicle.find("div", {"class": "vehiclePrices"})
                    getPrice = getPriceDiv.find("span", {"class": "price"})
                elif flags[1] == "4":
                    getPriceDiv = vehicle.find("div", {"class": "vehiclePrice"})
                    getPrice = getPriceDiv.find("span", {"class": "price"})
This works perfectly fine , but I figured the values in the dictionary would be flag[0], flag[1] and flag[2]. That however does not return the values I'd like. It returns: "(", "2" and "," respectively. So it seems the value of the dictionary is being treated as a string instead of a tuple. Which works, as long as I take the correct position of the string, but it's not what I had in mind.

fake edit: while I'm typing this I'm realizing my error. If I don't wrap the tuple in quotes, and remove the quotes from the if flags[x] == "value" it treats the tuple as a tuple instead of a string...

:ughh:

Yep, if you put something in quotes it's a string literal(people also use this for code comments in Python). It's actually not that different from how we use quotes in regular language. To steal part of an example from The Structure and Interpretation of Computer Programs:

Chicago is the largest city in Illinois.

"Chicago" has seven letters.

LochNessMonster
Feb 3, 2005

I need about three fitty


So now I've built my scraper/parser and put the data in a sqlite3 db, but now comes the presentation.

What's the easiest way to make a website do queries on the db to show the data. Can I do that with python too, or should I look into JavaScript for that?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

LochNessMonster posted:

So now I've built my scraper/parser and put the data in a sqlite3 db, but now comes the presentation.

What's the easiest way to make a website do queries on the db to show the data. Can I do that with python too, or should I look into JavaScript for that?

Ahh, well if I knew you wanted to make a website from the data I would have started you on Django from the start.

Since you've already got it in sqlite with your own schema, I'd probably use Flask.

No Javascript required.

LochNessMonster
Feb 3, 2005

I need about three fitty


Thermopyle posted:

Ahh, well if I knew you wanted to make a website from the data I would have started you on Django from the start.

Since you've already got it in sqlite with your own schema, I'd probably use Flask.

No Javascript required.

When I started I didn't have a real idea what to do, I'm just trying to learn and think qbout new things to do when I've finished something.

I was reading about Django and Flask a bit earlier and I was leaning towards Django as it appears to be a large framework which might suit additional features I might think about later. One of the thinks I'd like to do is pricetracking and visualize that with a graphing framework or something.

Flask seems to be in really early development (version 0.10). Does that matter?

Tigren
Oct 3, 2003

LochNessMonster posted:

When I started I didn't have a real idea what to do, I'm just trying to learn and think qbout new things to do when I've finished something.

I was reading about Django and Flask a bit earlier and I was leaning towards Django as it appears to be a large framework which might suit additional features I might think about later. One of the thinks I'd like to do is pricetracking and visualize that with a graphing framework or something.

Flask seems to be in really early development (version 0.10). Does that matter?

Django and Flask (with the right plugins) will accomplish the same tasks. When Django is advertised as "batteries included", it really means it. It includes database migrations, user authentication, admin panels, ORM, caching frameworks, etc. If you'll need all of that or even most of that, Django is an awesome project to work with and has fantastic documentation. We even have a Django thread here and people like Thermopyle are great helps in there.

If you just need an easy way to pull info from a sqlite database and throw it onto a webpage, look at Flask. It can do everything Django can, you'll just need to install each piece as an extension. Don't worry about the 0.11 version number. The project has been around for 5+ years and is very well maintained and mature. Pinterest and LinkedIn use Flask at scale, and I'm sure there are more examples.

Tigren fucked around with this message at 18:53 on Oct 16, 2016

LochNessMonster
Feb 3, 2005

I need about three fitty


Django sounds awesome, but it might be overkill for a newbie like me.

Will I be able to add other functionality (like creating graphs) to a Flask web application later on?

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

LochNessMonster posted:

Django sounds awesome, but it might be overkill for a newbie like me.

Will I be able to add other functionality (like creating graphs) to a Flask web application later on?

Yes. Flask is Just Python™ and you can use it to make just about any type of web app.

Tigren
Oct 3, 2003

LochNessMonster posted:

Django sounds awesome, but it might be overkill for a newbie like me.

Will I be able to add other functionality (like creating graphs) to a Flask web application later on?

The creating graphs functionality is entirely independent from your web framework. If you just want interactive visualizations, you can look into Bokeh, which is developed by BigRedDot. If you want to display those interactive visualizations along with other content, Bokeh will integrate with Flask very nicely.

LochNessMonster
Feb 3, 2005

I need about three fitty


Ok great to hear. Flask it is!

I noticed BigRedDot post some stuff about Bokeh in this thread, and that actually gave me the idea. It looks awesome and I can't wait to try it out, but first Flask.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

LochNessMonster posted:

Django sounds awesome, but it might be overkill for a newbie like me.

Will I be able to add other functionality (like creating graphs) to a Flask web application later on?

Flask is fine, but I want to beat the drum I beat every time this comes up (this isn't directed at you, I'm just throwing this out into the ether):

Django is batteries-included, but that doesn't make it inferior to Flask. It's kind of like python itself...just because Python has seemingly millions of libraries in its standard library doesn't mean that makes it hard or inferior in some way for writing a for loop.

You can use Django to write the web equivalent of Hello World in basically as minimal a fashion as Flask. A complete Django site:

Python code:
from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse

settings.configure(
    DEBUG=True,
    SECRET_KEY='A-random-secret-key!',
    ROOT_URLCONF=sys.modules[__name__],
)


def index(request):
    return HttpResponse('Hello World')

urlpatterns = [
    url(r'^$', index),
You don't get this idea when you first approach Django because all the tutorials want to expose you to everything Django can do.

The nice thing about starting out with Django is that when you want to expand your site's capabilities, those capabilities are "in the box". With Flask, you've got to find a third-party project (or write it yourself) that implements the functionality you want and cross your fingers that it's well maintained and has as many eyes on it watching it for security and quality as Django does.

The nice thing about starting out with Flask is that it's easier to get started with because the documentation and tutorials don't cover all the stuff that doesn't come with Flask.

Thermopyle fucked around with this message at 22:57 on Oct 16, 2016

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I haven't found many of Django's batteries to be useful, though. The comment system is mostly a joke.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Well you could say the same thing about Python itself. There's a lot of poor API's in the standard library. There's also lots of great stuff.

Same goes for Django.

In both cases, even a good portion of the poor libraries can at least get the job done in some manner.

Tigren
Oct 3, 2003

Suspicious Dish posted:

I haven't found many of Django's batteries to be useful, though. The comment system is mostly a joke.

You'll have to expand on this. Django's batteries, if and when you need them, are definately useful. The admin interface, ORM and auth system themselves are worth the price of admission. Throw in migrations and django-admin and you really are getting a lot of features out of the box.


Thermopyle posted:

Flask is fine, but I want to beat the drum I beat every time this comes up (this isn't directed at you, I'm just throwing this out into the ether):

Django is batteries-included, but that doesn't make it inferior to Flask. It's kind of like python itself...just because Python has seemingly millions of libraries in its standard library doesn't mean that makes it hard or inferior in some way for writing a for loop.

You can use Django to write the web equivalent of Hello World in basically as minimal a fashion as Flask. A complete Django site:

Python code:
from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse

settings.configure(
    DEBUG=True,
    SECRET_KEY='A-random-secret-key!',
    ROOT_URLCONF=sys.modules[__name__],
)


def index(request):
    return HttpResponse('Hello World')

urlpatterns = [
    url(r'^$', index),
You don't get this idea when you first approach Django because all the tutorials want to expose you to everything Django can do.

The nice thing about starting out with Django is that when you want to expand your site's capabilities, those capabilities are "in the box". With Flask, you've got to find a third-party project (or write it yourself) that implements the functionality you want and cross your fingers that it's well maintained and has as many eyes on it watching it for security and quality as Django does.

The nice thing about starting out with Flask is that it's easier to get started with because the documentation and tutorials don't cover all the stuff that doesn't come with Flask.

A similar Flask app:

Python code:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello world!'

if __name__ == '__main__':
    app.run(debug=True)
I agree that Django tutorials are often over complicated and make it hard to see the forest for the trees. I find Flask's syntax and setup easier for my uses, but I don't build complex web apps. I use the batteries so rarely that I don't mind throwing a Flask extension into my app when I need it.

Dominoes
Sep 20, 2007

For websites, I find Flask more difficult to work with than Django. It seems like a good idea at first, but most websites use several of the following: Database/migrations, admin, user accounts, email. Flask requires third-party plugins for these that don't necessarily play well together. Updates in one may break another, imports get messy, and the project is more difficult than if you'd started with Django. If you're making something other than a website that uses a webserver, Flask would be easier.

BigRedDot
Mar 6, 2008

LochNessMonster posted:

I noticed BigRedDot post some stuff about Bokeh in this thread, and that actually gave me the idea.

Let me know if I can answer any questions

Adbot
ADBOT LOVES YOU

Xarn
Jun 26, 2015
Probation
Can't post for 15 hours!
Need help with boto3 again :v:.

Is there a way to bypass JSON deserialization of incoming CloudWatch data? Having them in dict is nice and all, but one of my use cases is literally to write JSON to a file (that is then sent somewhere), and having the data flow go
code:
json from server -> boto3 deserialization -> python dict to my application -> dict to json serialization -> write json to gzipped file
gets in my grill (and costs me money, because its running inside of lambda).

  • Locked thread