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


huhu posted:

I tried to add
code:
@login_required
to my Flask app and now I'm getting an error when accessing those pages with that.
which led me to this page where it says:

However, I have the following in my view.py file:
*snip*
Isn't this a view named login?

I'm assuming that you are using Flask-Login here, but the gist of my advice should apply to you.

Somewhere in the code, Flask-Login is using this code to redirect your user to your login page:

Python code:
url_for('auth.login')
What that means is:
- Look for the Blueprint named auth and;
- Build a url for the login endpoint in the blueprint.

You are using @app.route, which means that your login endpoint is directly under the application object. There's nothing wrong with this per se, but blueprints are mostly used to organize code, which is a good thing. The biggest drawback is that, compared to the normal Flask way of creating routes, they have a bit of architectural overhead. That said, you have two options here:
1) Create an auth blueprint and put your login route in there;
2) Change Flask-Login's login route in the login manager.

Adbot
ADBOT LOVES YOU

Space Kablooey
May 6, 2009


Why don't you just use a localization library like Babel?

Space Kablooey
May 6, 2009



Flask admin views have the is_accessible and inacessible_callback methods to control who it lets access and how it should behave when an unauthorized user tries to access their pages.

For example:
Python code:
from flask_admin.base import BaseView
from flask import current_app

def is_accessible(self):
    return current_user.is_authenticated()


def inaccessible_callback(self, name, **kwargs):
    return current_app.login_manager.unauthorized()

BaseView.is_accessible = is_accessible
BaseView.inaccessible_callback = inaccessible_callback

Space Kablooey
May 6, 2009


If you add items like you did in your example, you should be fine.

The problem is when you do it like this:

Python code:
from collections import OrderedDict
a = OrderedDict({'a': 1, 'b': 2})
b = OrderedDict(**{'a': 1, 'b': 2})
c = OrderedDict(a=1, b=2)
In all of these examples, Python uses a regular dict to create the OrderedDict, and since regular dicts aren't ordered, you will lose the order that you want.

Space Kablooey
May 6, 2009


It's right there on the quote that you should not rely on that ordering. :psyduck:

Space Kablooey
May 6, 2009


I try to start with None or a boolean value if I don't have a default value that makes sense.

Space Kablooey
May 6, 2009


Sorry to be unspecific, but in that case you have to analyze whatever makes the most sense to you and work around the code's limitations.

Space Kablooey
May 6, 2009


huhu posted:

I've got a login form and a registration form on a single page with a nav that toggles a hidden class between the two. By default, when the page loads, registration is set to hidden. However, if a user fills out the registration form and there are errors on submit, the page refreshes and login is loaded. How could I get the hidden class to instead be applied to registration if a user registers but has errors?

Pass a flag to the template and, depending on the state of the flag, apply (or not) the class to the offending elements.


Python code:
@app.route('index/')
def route():
    return render_template('index.html', flag=True)
HTML code:
<div {% 'class="hidden"' if flag %}>
</div>

Space Kablooey fucked around with this message at 04:43 on Mar 17, 2017

Space Kablooey
May 6, 2009


It's throwing a syntax error because it's missing the except clause.

By the way, you can rewrite any file opening operation as:

Python code:
with open('filename') as file:
    # ... Do things with the file
#... Program goes on
Doing this way makes Python close the file automagically.

Space Kablooey
May 6, 2009


Lysidas posted:

except clauses are not required if there's a finally.

Neat. I didn't know about that.

Space Kablooey fucked around with this message at 13:45 on Mar 24, 2017

Space Kablooey
May 6, 2009


nvm

Space Kablooey fucked around with this message at 15:32 on Mar 30, 2017

Space Kablooey
May 6, 2009


funny Star Wars parody posted:

Ok here's a dumb question: I want to make a unicornhat (which uses a Python library) on a raspberry pi do something when a new order is placed, and according to the Shopify API, you would use their webhook to do it and you supply them with the URL for the webhook to deliver a HTTP POST payload to in json format.

I understand the concept of json stuff after working with the discord API but I've never worked with webhooks before, so correct me if I'm wrong but does that mean I have to have my own server running and listening for the HTTP POST payload? Since it's a raspberry pi would it be easier to try to sniff for like an email notification to trigger the light_sign action?

Any pointers would be great, I'm doing this for a friend's company in exchange for some of the neat t-shirts that he sells so I'd really like to find a way to make it work that doesn't take me a million years to figure out

Yes, that is correct. Your URL should point to a live server that is expecting a POST with the format that Shopify sends you. I don't know any specifics of Raspberry, so I can't really help you with your second question.

Space Kablooey
May 6, 2009


funny Star Wars parody posted:

I use Python 2.7 anyways so yayyy

Edit: how much does Zappa cost amper month for a server for a single webhook that is triggered maybe 5-10 times per day?

The pricing depends on Amazon Lambda's pricing, but you will probably be well within the free tier.

Space Kablooey
May 6, 2009


Dominoes posted:

Re Flask vs Django: Django for websites, Flask for other things you need a webserver for. Flask becomes a pain once you start adding plugins for things like admin, auth, migrations, databases etc.

Outside of a very specific library (Flask-Social), I had no issues with any Flask extension so far.

I'll give you that it's easier than Django to make a mess of packages and modules and dependencies when your project grows.

Space Kablooey fucked around with this message at 03:25 on Apr 1, 2017

Space Kablooey
May 6, 2009


The error is pretty straightforward, item['link'] is a list of somethings (or it could be empty). You can try printing it out and seeing if whatever you want is in there, and then you can concatenate with your follow link.

Space Kablooey
May 6, 2009


I'd indent the other conditions and invert the any to get rid of the pass, otherwise it looks fine to me.

Space Kablooey
May 6, 2009


Can someone explain to me what's going on here:

Python code:
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = []
>>> x.append(x)
>>> x
[[...]]
>>> x[0]
[[...]]
>>> x[0][0]
[[...]]
>>> x[0][0][0]
[[...]]
>>> 
I ran into this when I was mistakenly appending a list to itself, but I'm intrigued as to what's going on here.

Edit: nvm, it's pretty obvious.

Space Kablooey fucked around with this message at 18:31 on Apr 10, 2017

Space Kablooey
May 6, 2009


QuarkJets posted:

sorry i meant

[_ for _ in range(0,1,1)]

i thought you knew that _ is also completely uninformative. i think you meant [unused for unused in range(0,1,1)]

Space Kablooey
May 6, 2009


Cingulate posted:

For real though, how did you oldsters ever live with Python 2 and its leaking list comps?

You mean the leaking variable that is used on building the comps or you mean like a memory leak or something like that?

How to live with the former is to just redefine the name before reusing.

Space Kablooey
May 6, 2009


I'm not sure if I dislike comprehensions leaking, tbh.

Python code:
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> for y in range(10):
...  print(y, end=' ')
... 
0 1 2 3 4 5 6 7 8 9
>>> y
9

Python 2.7.12 (default, Jul  1 2016, 15:12:24) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
9
>>> for y in range(10):
...  print y,
... 
0 1 2 3 4 5 6 7 8 9
>>> y
9
The Py3 example feels inconsistent to me, in the sense that the comprehension doesn't leak while the for does, but that might just be because I'm more used to Py2.

Space Kablooey fucked around with this message at 14:16 on Apr 13, 2017

Space Kablooey
May 6, 2009


I still think subclassing is the better option, if anything because it is the simplest way.

Space Kablooey
May 6, 2009


Symbolic Butt posted:

Most likely yes. If you make it explicit that the number part is an integer you'll get the sorting you want:

>>> ('file', 2) < ('file', 10)
True
>>> ('file', '2') < ('file', '10')
False

I didn't know you could compare tuples like that. :aaa:

Space Kablooey
May 6, 2009


Eela6 posted:

pathlib Paths are hashable and orderable (and therefore sortable) so you can just call sorted!
*snip*

Death Zebra, can you give us the full stack trace?

How does it deal with a folder that has file1, file9, file10 and so on?

Space Kablooey
May 6, 2009



Just had a quick glance at it, but you could use os.path.splitext to check the file extension. use the suffix property from Path.

Space Kablooey fucked around with this message at 21:21 on Apr 24, 2017

Space Kablooey
May 6, 2009


huhu posted:

I've just finished my first Flask project for my new job which is basically a page with a form that allows users to do CRUD operations on a database table. It took me about a week to create. Of course there was a bunch of stuff like having to learn MySQL, JavaScript form validation, navigate their code base, etc. along the way so it took a bit of time. I was just able to recreate what took me about a week with Flask Admin in an hour and was even able to add additionally functionality like a list view, searching, and filtering. I feel like this was deceptively simple though and when I start working on more complex projects I'd be better off writing the SQL and JS myself. Is that correct?

At some point yes, you will have to customize something or other, but Flask Admin really is that powerful.

Space Kablooey
May 6, 2009


The liquor store?

Space Kablooey
May 6, 2009


I think it depends on the protocols, IIRC.

If you are using HTTP/S you have to make one request per connection, but if you are using TCP or UDP you could make something like that, but I wouldn't know how with requests, but it shouldn't be too hard.

Space Kablooey
May 6, 2009


I think your case right now is a really good starting point for learning about classes! Unfortunately I don't have a suitable beginner guide on those on hand right now, but you could just google "classes in python" or something like that and start from there.

Also:

Mirthless posted:

tbh the constant nagging feeling that i'm doing it wrong makes programming really discouraging :(

Whenever you get that "There has to be a better way of doing this" feeling, you should reach out and ask. Especially if you just starting out programming.

Space Kablooey fucked around with this message at 15:38 on Jul 5, 2017

Space Kablooey
May 6, 2009


Yeah, that's a job for a rq or celery setup.

Space Kablooey
May 6, 2009


If you still want to use virtuaenv, you should take a look into at virtualenvwrapper which is a set of convenience scripts over virtualenv (meaning source virtualenv/bin/activate becomes workon <name_of_env> and so on).

I think the new hotness is pipenv, though, but I never used it.

Space Kablooey
May 6, 2009


So a friend of mine is about to start a Python programming job, and he asked me if I had any Python beginner resources. I recommended Fluent Python and Think Python, but I'm not sure if there's more than that that's highly recommended.

Fake edit: Nevermind, I found this huge list in the Python website: https://wiki.python.org/moin/BeginnersGuide/Programmers

Space Kablooey fucked around with this message at 03:22 on Jan 26, 2018

Space Kablooey
May 6, 2009


I mean you could (and should) make that into a function, but you can get the token by doing requests.json()['data'][0]['token'] directly.

To expand, request.json() returns a python dictionary (and not a string), that is, in short, a data structure that maps keys into values. So, for that particular dictionary, your token is inside a dictionary, under the key "token", that is inside a single element list (so index 0), that is inside another dictionary, under the key "data".

Space Kablooey
May 6, 2009


Sqlalchemy .one() returns exactly one result or returns an error

.one is a bit of a minefield on SQLAlchemy to say the least. IME it's more intended to be the execution of a string of filters, and then to validate if there's exactly one of a record with that criteria, and, lastly to return it. It will raise errors if there's no record matching that criteria or if there's more than one record matching that criteria.

If you just want one object and don't care which record it is, you should use .first instead. Be aware that this will be the first record found by the database, which may or may not be ordered according to the primary key(s).

Space Kablooey
May 6, 2009


No problems!

I've worked with SQLA for a long time and I still make that mistake when I'm writing one-off scripts far more often than I'd like.

I have no clue why it takes hours for you, though. Hopefully .first will be much, much faster.

Space Kablooey
May 6, 2009


Python code:
for method in commandlist:
 response = getattr(client, method)()
Also you should use context managers for dealing with files:
Python code:
with open("path/to/file", 'w') as file:
 file.write(content)
In that way, when you leave the with block, the file will be automatically closed.

Space Kablooey
May 6, 2009


Which testing framework is the new hotness nowadays? I've been using nose for the longest time and I want to get on with the times.

Space Kablooey
May 6, 2009


Hypothesis looks pretty cool, thanks.

Space Kablooey
May 6, 2009


I never used webbrowser before, but reading the docs, you should either:

1) Use webbrowser.open and just pass the URL, and the system will open the given URL in the default browser, or
2) If you actually need a reference to the browser controller, you just need to pass the name of the browser to webbrowser.get, and then use one of the open methods listed.

Adbot
ADBOT LOVES YOU

Space Kablooey
May 6, 2009


{item['Key']: item['Value'] for item in n['Tags']}

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