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
Space Kablooey
May 6, 2009


I'm the horror because I didn't even read the assignment :smith:

Also, check the indentation of the __init__ method of the TemperaturePlotApp.

Adbot
ADBOT LOVES YOU

Space Kablooey
May 6, 2009




I managed to reproduce it.

On my first run, every time I picked the powerups, they worked normally. When I'm kicked back to the title screen because I lost three lives, I start over and pick the powerup. Starting on this run, the bug appears every time, without fail.

My guess is that you are forgetting to clean something between runs.

Space Kablooey
May 6, 2009


If you were on Unix you could have done something like

code:
$ projectfolder/veenv_folder/bin/python projectfolder/manage.py runserver
I'm not really sure how is it on Windows, but I think it's the same.

Space Kablooey
May 6, 2009


EAT THE EGGS RICOLA posted:

Is there a clean way for me to get the next item in a jinja2 loop without incrementing the loop or installing an extension that allows it?

I just want to do this cleanly:

HTML code:
    {% for thing in thing_list %}
	{{ thing.id }}
        {{ thing.next().id }}
    {% endfor %}

If I need to compare stuff between runs of a loop I usually do something like this:

HTML code:
    {% set last_id = None %}
    {% for thing in thing_list %}
        {% if last_id is None %}
            {% set last_id = thing.id %}
        {% endif %}
        {{ last_id }}
	{{ thing.id }}
        {# do stuff #}
        {% set last_id = thing.id %}
    {% endfor %}
However, this IMO is almost the opposite of cleanly, but IDK how to do differently.

What exactly are you trying to do?

Space Kablooey
May 6, 2009


Something like this?

code:
def __init__(self, butt):
    custom_fields = butt['custom_fields']
    for k, v in custom_fields.iteritems():
        setattr(self, k, v)
That has the problem that the fields that aren't in the custom_fields won't exist in the instance, I don't know how much of a problem it will be.

Space Kablooey
May 6, 2009


Personally, if I was sure that those fixed fields won't change any time soon, I would do
code:
    def __init__(self, **kwargs):
        self.name = kwargs.get('name')
        self.id = kwargs.get('id')
        self.email = kwargs.get('email')
        self.active = kwargs.get('active')

Space Kablooey
May 6, 2009


I'm not really sure what you are not understanding. Can you explain a bit more in depth?

One thing in the meantime that you can do to hopefully make thing a bit clearer for yourself, is to add a few prints inside the for loop, for example, to print out the l and sum variables.

Space Kablooey
May 6, 2009


Thermopyle posted:

As far as the extra work of using virtualenvs...look into using virtualenvwrapper. It makes it easier. I think there's a branch for windows.

It's a bitch and a half to install it on windows, but it's well worth it.

http://www.tylerbutler.com/2012/05/how-to-install-python-pip-and-virtualenv-on-windows-with-powershell/

Space Kablooey
May 6, 2009


I thought pip was the "default" package manager/installer.

Space Kablooey
May 6, 2009


SurgicalOntologist posted:

"Default" is the wrong word here, I think baka kaba meant more along the lines of "most recommended". It is (in my opinion) "what the average person should install to get coding with minimal fuss."

Ah, sure, that makes sense.

As far as I can recall, except for installing lxml (:v:), I've yet to have a really bad experience using pip.

Space Kablooey
May 6, 2009


duck monster posted:

Reposting this here because it might be of interest to those who also believe Python is the language of the master race, and javascript on mobile devices needs to die:


I'm intrigued, please tell me more.

Space Kablooey
May 6, 2009


If you are already using Flask for the API, why not go whole hog? Are you having any specific difficulties using Flask?

Space Kablooey
May 6, 2009


I'm biased because I'm working with Flask for three years now, and I strongly prefer it over Django overall. Something about Django just doesn't click with me for some reason, because every time I start a Django project to try and learn it, it feels bloated right out of the gate.

Having said that, for you project in particular you might need a lot of tuning for how each user's queue should behave (what jobs should appear in each queue and so on), and that will probably imply in a lot of tuning of your models. And for that, you will probably need a decent administrative interface, and Flask-Admin isn't quite there yet in terms of flexibility IMO (It's either a fairly rigid set of basic CRUD views or it's a completely blank template for you to build upon). Apparently Django's admin is better, but I really can't say how and where.

Another sore spot for Flask vs Django is the social login, were Django's has to be better because every Flask extension that I worked with so far was kinda poo poo.

Having said all that, though, if you have the time and the inclination to do that, I would suggest building your front-end in both frameworks so you can then compare them much better that way. Your application logic shouldn't have anything to do with your web framework anyway.

If you have any Flask questions, though, feel free to ask.

Space Kablooey
May 6, 2009


5436 posted:

Is it possible to simply program the service portion in flask and use something else for the front end? Well I guess I know its possible but is it optimal to getting off the ground quickly? I'm not really a developer so I haven't made a web app before.

I think you can, but I don't think there's any point to using something else than flask specifically for the front-end, since it already does have something to both render your templates in the server (Jinja2) and to serve the rendered template as a HTML page.

Space Kablooey
May 6, 2009


There may be other options that don't depend on an external lib, but :effort: . Did you try using unicodecsv? (Install it using pip install unicodecsv)

Space Kablooey
May 6, 2009


If you can use a shared hosting, then I can't see why not use that.

Failing that, I use nginx + uWSGI. The biggest problem so far is that uWSGI prevents me from upgrading to Python 3. :( Otherwise, it works fine for me.

Space Kablooey fucked around with this message at 13:30 on Dec 14, 2015

Space Kablooey
May 6, 2009


That's nice, then.

I checked the WoS and uWSGI is listed as not supporting Python 3, and I thought that it couldn't run applications made with Python 3.

Space Kablooey
May 6, 2009


sum assumes that the start value is the integer 0.

You should use ''.join(['Ehgi', 'Hu']) for concatenating a list of strings, though.

Python code:
>>> sum(['Ehgi', 'Hu'], '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

Space Kablooey fucked around with this message at 21:03 on Feb 1, 2016

Space Kablooey
May 6, 2009


KernelSlanders posted:

I'm continually amazed how Windows manages to mangle files. We bought some Bing search ads and hooked up our normal analytics pipeline to their API to download some CSVs that say how the ads did. Care to guess how it broke?

Trick question. The API broke.

Space Kablooey
May 6, 2009


If symbols were a relationship I would do:

Python code:
s.query(a).filter(a.symbols.in_(symbol), a.published >= day, a.published < day + dt.timedelta(days=1)).all()
I'm not really sure that this will work in your case, considering your symbol is (probably) a string and not a relationship.

Space Kablooey fucked around with this message at 22:07 on Feb 28, 2016

Space Kablooey
May 6, 2009


You should take a look into converting into Declarative Base, if at all possible.

If you can't or won't, you shouldn't override filter_by to return a list (using .all()). Instead return the BaseQuery that the regular filter_by returns.

Space Kablooey
May 6, 2009


Then why are you using db.session.query(Model) instead of declarative base's Model.query? It sounds it's what you want regarding SQLAlchemy's verbosity.

As for not returning the list, usually you can chain any other query clause (say a .join, other .filters and so on) as long the methods return a BaseQuery object. If you hide the .all() inside your override, you'll just create confusion down the line.

Besides, BaseQueryes can also function as a generators:

Python code:
for item in Model.query.filter_by(name="butt"):
    print item

Space Kablooey
May 6, 2009


Dominoes posted:

The code I posted is straight from the declarative base page you linked. AttributeError: type object 'Person' has no attribute 'query', and I can't find your syntax on that page, although I've seen it mentioned before. Can you provide an example of querying from the model, without the syntactic sugar I posted?

Actually I can't. :(

Apparently what I said is a bunch of poo poo that Flask-SQLAlchemy adds on top of SQLAlchemy to make it more palatable, and I'm so used to writing queries in that way that I didn't know it wasn't a default thing. Sorry for that. :(


Dominoes posted:

Regarding queries as generators: Per this article, they're not lazy:

I should have said "behaves like" instead of "functions". My point still stands, though. You really shouldn't gobble up the Query object returned by the db.session.query function.

Besides, a few database drivers do support database cursors. Postgres' psycopg2 does, for example. Though if SQLAlchemy does take advantage of that or not, I don't know.

Space Kablooey
May 6, 2009


Does anyone know if it is it possible to run UWSGI from a Raspberry Pi? AFAIK you can run PyPy on it, but I'm not sure if it just works with my current application set or if I have to whip up something else.

I don't have a Pi or else I would test it myself. :smith:

Space Kablooey
May 6, 2009


Wow, thank you! :3:

Any specific headaches? Are you running Noobs or Raspbian? Do you have to run PyPy or does cPython work?

Can you test Flask on it, please?

Space Kablooey
May 6, 2009


It seems to be working to me. Try accessing localhost:8080.

Space Kablooey
May 6, 2009


Probably because it needs an nginx running as well. But uWSGI seems to be working. Thanks a lot for that!

Space Kablooey
May 6, 2009


Loving Africa Chaps posted:

I'm trying to get started with python having used php in the past and i'm tearing my hair out at what should be something really simple.

I'd like to iterate through a list of twitter ID's, check if they're already in a database and if not add them. For the loving life of me i can't seem to get a simple query to work at all. Every time i google for an answer people are using a slightly different way of writing a query.


Python code:
	cursor2 = mariadb_connection.cursor()
	query = ("SELECT * FROM foamites WHERE twithandle= %s")

	#scrape using the twitter api
	#this bit works and i print to a .txt
	twitterid = user.id

    cursor2.execute(query, twitterid)
    numrows = cursor2.rowcount
    	
	#if doesnt return anything 
	print "not in database"


What's the error you are getting? Also, don't mix tabs and spaces. When I quote it looks like they are mixed, but not in the post? :confused:

Space Kablooey
May 6, 2009


Feral Integral posted:

So I'm working on a project that is going to soon require me to run long-running calculation jobs which are all viewed/edited/created through a django site. Whatever is going to run the jobs will ideally be able to run multiple jobs at a time without blocking other jobs, as well as be able to give status info about running jobs when asked for it.

Is there a good python framework with lots of included bells and whistles for this kind of thing anyone might recommend, or any suggestions from people that have tackled something similar?

edit: http://python-rq.org/docs/workers/ looks p cool

We use rq for that and it works nicely. You can also take a look at celery, which is a bit more complex, but it seems more powerful in general.

Space Kablooey
May 6, 2009


Try installing whatever with pip3. Oh no wait, it actually installed. Dunno then.

Space Kablooey
May 6, 2009


jon joe posted:

Which is better:

code:
dict = {}
def populate(key, tuple):
    if key in dict:
        dict[key][tuple[0]] = tuple[1]
    else:
        dict[key] = {}
        dict[key][tuple[0]] = tuple[1]
vs

code:
dict = {}
def populate(key, tuple):
    try:
        dict[key][tuple[0]] = tuple[1]
    except KeyError:
        dict[key] = {}
        dict[key][tuple[0]] = tuple[1]

If you don't want to go with defaultdict (why wouldn't you), it think the snippet below is nicer.

Python code:
def populate(key, tuple):
    if key not in dict:
        dict[key] = {}
    dict[key][tuple[0]] = tuple[1]

Space Kablooey
May 6, 2009


priznat posted:

Hey all,

Quick question, I've got a python & flask project (displaying test results pulled from a sql database) and looking to deploy it to a proper webserver.

What would be the best webserver for this, if it has a relatively low workload (only 10 or so users max)? My first thought was apache/mod_wsgi but I had a look around and saw CherryPy and it looks ridiculously simple to get going.

Also is it worth setting this kind of thing up in a docker container or nah? Running on a CentOS 7 minimal VM in Hyper-V.

I prefer using uwsgi instead of gunicorn, but the result is the same and the effort required is not much different.

There's this guide by the same person that sets up uwsgi, but I think all the configuration he did was a bit overkill, especially the upstart script.

Space Kablooey
May 6, 2009


Didn't know that, thanks.

I don't think I use the defaults myself because I got an init script from someone else that worked with uwsgi. The file wasn't exactly extensive, but it wasn't long enough to warrant (for me) a separate file for configuration.

Space Kablooey
May 6, 2009


LochNessMonster posted:

When using the for loops I keep getting the same error, no matter what I try.

When running this:
Python code:
import sqlite3
conn = sqlite3.connect('vehicles.db')
cursor = conn.cursor()

testList = [{'DealerId': '2',
            'Brand': 'bmw',
            'Milage': '13.909',
            'Dealer': 'crazy jack',
            'Price': '5.000',
            'Type': 'r90',
            'Year': '1980'},
            {'DealerId': '3',
            'Brand': 'goldwing',
            'Milage': '15.564',
            'Dealer': 'Mohawk Mike',
            'Price': '8.000',
            'Type': 'goldwing',
            'Year': '2015'}]


for dictionary in testList:
    cursor.execute("INSERT INTO motorcycles VALUES(?, ?, ?, ?, ?, ?, ?)",
                   dictionary["DealerId"],
                   dictionary["Dealer"],
                   dictionary["Brand"],
                   dictionary["Type"],
                   dictionary["Price"],
                   dictionary["Milage"],
                   dictionary["Year"])
I keep getting:

code:
Traceback (most recent call last):
  File "/path/to/program/dbinsert2.py", line 29, in <module>
    dictionary["Year"])
TypeError: function takes at most 2 arguments (8 given)

Tigren's solution is the better one IMO, but according to the docs (https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute), if you want to use dictionaries, you have to use the named parameters style instead of the question marks one.

The question marks style is used when you have a list or tuple with the parameters already in order, for example:

Python code:
x = ['gassy', 'smelly', 'loud']
cursor.execute("INSERT INTO farts VALUES(?, ?, ?)", x)
If you wanted to use dicts, you would use it like this:

Python code:
x = {'type': 'gassy', 'smell': 'smelly', 'noise': 'loud'}
cursor.execute("INSERT INTO farts VALUES(:type, :smell, :noise)", x)
And it should work. I'm not sure the dictionary keys have to be equal to the columns names, but I don't think so.

Space Kablooey fucked around with this message at 16:00 on Sep 22, 2016

Space Kablooey
May 6, 2009


A department of my job also works with parsing data scraped from disparate websites and they learned that even if the sites are similar or share some parsing code, you are better off treating each site as a special snowflake.

Granted, if in your case the sites are similar enough, you might be able to get away with creating a framework of sorts for parsing, and abstracting away the specific parts for each site, and implementing it on specific modules/packages for each site.

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

Space Kablooey
May 6, 2009


Minor nitpick on your query_db function.

When you want to return only one result, you shouldn't pick the first result from cur.fecthall, you should use cur.fetchone instead, like so:

Python code:
def query_db(query, args=(), one=False):
    cur = get_db().execute(query, args)
    if one:
        rv = cur.fetchone()
    else:
        rv = cur.fetchall()
    # or you can replace the if else with 
    # `rv = cur.fetchone() if one else cur.fetchall()` if you are feeling cheeky
    cur.close()
    return rv

Space Kablooey
May 6, 2009


ahmeni posted:

Does anyone have a pattern for logging requests in Django Rest Framework that they like? The only real solution I've seen is a middleware that requires a mixin for each APIView, which isn't too bad but I'd prefer something a tad less fiddly.

Isn't this the kind of thing that it's better if you do in your server instead of the application?

Space Kablooey
May 6, 2009


lifg posted:

Does anyone have experience or recommendations on building Python software with virtualenv and Docker?

I've used them both for toy applications, but not together. They seem to solve the same problem, just at different levels, so I don't *think* there's a benefit to using virtualenv if I'm also using Docker.

I've never used virtualization (of any sort) for software development, so this is all new to me.

I'm also quite new to Docker but in my experience, yeah, you really don't exactly need to ensure that the container's Python environment is clear, after all that's what the Docker container is for.


I'd love to hear from someone that has more experience with Docker, because I still can't wrap my head around on how to do some things, most importantly on how to update code and few other stuff.

Adbot
ADBOT LOVES YOU

Space Kablooey
May 6, 2009


Boris Galerkin posted:

I'm trying to learn/use Sphinx but I swear every single tutorial I've found is completely worthless and leaves more questions than answers. For example I just want to do something simple like this:
*snip*

Do you know any OSS project that does what you want in their documentation? I never came across this before.

  • Locked thread