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
huhu
Feb 24, 2006
I'm reading about RESTful web services as they relate to Flask. In the introduction, It talks about how you might need to have multiple versions of your website because not everyone can access the new version immediately (i.e. a smartphone app won't be up to the newest version until the user downloads the new version). The smartphone app was the only example given and I'm struggling to understand what else would justify having separate versions of a website with Flask?

Edit: Perhaps a better question, is there a good article/resource that explains RESTful web services well?

huhu fucked around with this message at 19:23 on Mar 8, 2017

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006
I tried to add
code:
@login_required
to my Flask app and now I'm getting an error when accessing those pages with that.

quote:

werkzeug.routing.BuildError: Could not build url for endpoint 'auth.login'. Did you mean 'login' instead?
which led me to this page where it says:

quote:

The default is login but since you don't have a view named 'login'
However, I have the following in my view.py file:
code:
@app.route('/login', methods = ['GET','POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, remember= False)
            return redirect('/web_viewer')
        flash('Invalid username or password.')
    return render_template('login.html', form=form)
Isn't this a view named login?

huhu
Feb 24, 2006

dougdrums posted:

You might have done this, but the login manager class has a field "login_view" that can be set, like
code:
login_manager.login_view = "users.login"
at https://flask-login.readthedocs.io/en/latest/#customizing-the-login-process

I just realized I was using the login extension wrong, I'm glad you asked this ...

I've never done any web-dev before, and despite c# being my goto language I decided to follow https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world up to the point where openid gets involved. I really like using flask, sqlalchemy, the whole bit is really good when I don't really know what I'm doing python-wise. I really like writing python3 though, and it's super loving easy to read other's python3 code.

I just can't handle the runtime type checking though, it makes me real uneasy. I annotate all of my functions and still gently caress everything up all of the time. The best fuckup was when I passed a string into a function that was supposed to take a list of strings and make directories out of them ...

I guess I have two questions for the thread:
- Is there an advantage to annotating my function definitions beyond having some documentation?
- Is there a less heavy handed way to do m:n style threading in python besides using celery/rabbitmq? I'm looking for something like .Net's Task Parallel Library or whatever Go does.


vvv lol now if I can only get this web app to read forum posts for me i'd be solid

Thank you so much.

huhu
Feb 24, 2006
:woop: My first Flask application is almost done. Hopefully one last question. I've setup Flask-Admin and it works well by routing all traffic (even non logged in users) from /admin to the admin panel. However, /admin is not a route in my views.py file. I thought I could just do something like:
code:
@app.route('/admin', methods = ['GET','POST'])
@login_required
def admin():
    #admin stuff here
but since Flask-Admin handles this route differently, this doesn't seem to be possible. Flask-admin suggests using Flask-Security to do this. Would this just be the easiest way or is there some easy fix to the method I was thinking above?

huhu
Feb 24, 2006
This code
code:
import sys

#TB I need to setup virtual env

activate_this = '/home/huhu/.virtualenvs/wv_venv/bin/activate_this.py'
exec(activate_this, dict(__file__=activate_this))

sys.path.append('/home/tbumgarner/webapps/chs_web_viewer/web_viewer')
import app as application
is leading to this error. I for the life of me have no idea why this is happening.
code:
[Sun Mar 12 20:10:50.924896 2017] [wsgi:error] [pid 7297:tid 139694796572416] [remote 127.0.0.1:50826]

     exec(activate_this, dict(__file__=activate_this))
   File "<string>", line 1
     /home/huhu/.virtualenvs/wv_venv/bin/activat$
     ^
 SyntaxError: invalid syntax
I was following this tutorial and had to change the execfile() command for python3.

huhu
Feb 24, 2006
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?

huhu
Feb 24, 2006
Would this be the best way to log errors on a script that I'm running?

code:
try:
    # Threading here for 3 different functions
except Exception as e:     
    logf = open("log.txt", "a")
    logf.write("Error: {} \n".format(str(e)))
    logf.close()
finally:
    pass

huhu
Feb 24, 2006
Awesome thanks for the quick replies!

huhu
Feb 24, 2006
Curious if anyone would be interested in a Flask thread? I'm starting a new job working full time with it and would love a place to discuss it more.

huhu
Feb 24, 2006
I decided to write a Flask intro for anyone that is curious.

Why Flask?
In my opinion, Flask feels like just another package you would want to use on a project. It is simple to use and very modular. You only add new functionality – such as support for login, if you need it. It also does a great job of letting you write almost solely Python. For the backend, the database can be created without having to write SQL statements. On the frontend, forms and other page content can be created with Python instead of JavaScript. If you would prefer not to write CSS/HTML you can find pre-made static templates that are easy to integrate. Finally, it’s nice to be able to not have to deal with PHP.

How to get started
Both the book and tutorial are resources by the same author and they are awesome. I would recommend reading through both.
Flask Book
Flask Tutorial
Flask Documentation

What can it be used for?
I’ve used it to build simple static websites and as a way to serve content, specifically images from a security camera, from my server. Additionally, I followed a tutorial for building a blog. For my new job, I’ll be building dashboards for scientists to access and analyze their data.

Basic Demo
Setup
The basic setup steps are to install a virtual environment, activate it, and then install Flask.
code:
virtualenv venv_sa 
venv_sa\Scripts\activate.bat 
 pip install flask
Directory Structure
The directory stucture consists of the folder for the virtual environment, hello.py which is defined below, and a templates directory. Templates are written in HTML and data from databases or other sources can be added to them before they are returned to the end user as a webpage.
code:
hello.py
templates/
    user_page.html
venv_sa/
Hello.py
The code below starts with declaring a new instance of Flask named app. To the app we add routing which is how we figure out what information we want to send back to the user. The first route, '/' which points to index() will return "Hello World" when a user visits https://www.website.com/. The second route is a little special. If someone visits https://www.website.com/user/huhu, the string 'huhu' will be passed to the user_page() function. Additionally user_page() also has a current_time which gets the current time. These two bits of data are then added to the 'user_page.html' template with the render_template() function.
code:
import datetime
from flask import Flask, render_template

app = Flask(__name__)

# Routing
@app.route('/')
def index():
    return "Hello World."

@app.route('/<username>')
def user_page(username):
    current_time = datetime.datetime.now()
    return render_template('user_page.html', username=username, current_time = current_time)

if __name__ == '__main__':
    app.run(debug=True)
user_page.html
This template takes username and current_time from the user_page() function above, adds the data to the template, and then returns it to the user.
code:
Hello {{ username }},<br>
The current time is {{ current_time }}.
Launch the app
The last step is to simply run the following command and the app will start:
code:
python hello.py
The website can be viewed at 127.0.0.1:5000.

huhu
Feb 24, 2006

Ghost of Reagan Past posted:

What's a good library for drawing an array of pixels? They would change over time (I'm not animating figures, though), and I plan on eventually feeding into some LEDs, but for now I'd rather prototype without wiring up a bunch of LEDs. I've thought of just doing it with Flask + Javascript but I'm wondering if there's some other good solution.

I'm semi-willing to use some other language, but Python's the language I use daily so I'd rather just stick with that unless I can't find an adequate solution.

https://python-pillow.org/

Edit: How many LEDs are you talking about by the way? Are you planning to use Arduino, Raspberry Pi, or something else?

huhu
Feb 24, 2006

Ghost of Reagan Past posted:

32x32 and a Pi for the prototype. We'll see whether a Pi can do what I actually have in mind at the end of the day, but I'll get there when I get there. But on a computer I can have a much higher resolution I'm probably gonna start with that. I'm okay with this taking a lot of iteration and work.

Well that's pretty easy. I could probably write it to render at 20fps or whatever.

praise be to numpy

Definitely go Python. It works very well with the Pi, if you didn't already know that.

If you got money to burn, a guy at my hackspace built a really nice Neopixel 10x10 grid.
https://www.adafruit.com/products/1138

huhu
Feb 24, 2006
I'm starting to run into more advanced packages that are requiring things like Microsoft Visual C++. I've also been reading about how some things are too slow in Python so other languages are used to deal with this. Is there an article/video that explains this all well?

huhu
Feb 24, 2006

Dominoes posted:

Broad topic. Many python modules use C code to improve speed. When installing them from source, (Including pip without a wheel) you'll need a compiler; Visual C++ is used in Win. Which package are you referring to? You can usually avoid this by using Conda, or a Chris Gohlke binary.

To speed up Python, you can use Cython, Numba, vectorized code, PyPy etc, on the bottlenecks. What specifically do you want to know?

You've given me enough vocab I had to look up that I more or less understand what I need to know now.

huhu
Feb 24, 2006
I started developing with Sublime Text and then switched to PyCharm since I've been working mostly with Python. However, my new job has me focusing on Flask apps and PyCharm seems to be a bit lacking when it comes to dealing with HTML, CSS, and JS. I miss all the awesome plugins that come with Sublime Text as well. Am I missing something or should I be looking at something else to be developing Flask stuff?

huhu
Feb 24, 2006

The Fool posted:

I feel like I might be saying this too often at this point, but have you considered VSCode accepted Christ as your Lord and Savior

https://code.visualstudio.com/docs/languages/python

This is amazing.

huhu
Feb 24, 2006

Thermopyle posted:

What?

PyCharm is amazing for HTML/CSS/JS. It's basically a superset of Webstorm which is already widely liked for webdev stuff. I often use PyCharm for projects that are only HTML/CSS/JS.

Maybe ask about some specific things you're missing and I bet you'll find that most of them are supported.
VS just does everything I thought Pycharm would do right out of the box.

huhu
Feb 24, 2006

Cingulate posted:

Different question: does Continuum make money? What are the chances "conda install all_the_software_i_need" won't work in 2018 because Travis Oliphant has to choose between making it slightly easier for me to set up numpy or feeding his kids?

2018? I don't think anything is guaranteed 3 months from now.

huhu
Feb 24, 2006
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?

huhu
Feb 24, 2006
In Pycharm, is there a way to run code and then and then leave some sort of a command line to continue playing around with it?

Thermopyle posted:

What?

PyCharm is amazing for HTML/CSS/JS. It's basically a superset of Webstorm which is already widely liked for webdev stuff. I often use PyCharm for projects that are only HTML/CSS/JS.

Maybe ask about some specific things you're missing and I bet you'll find that most of them are supported.

VisualStudio feels like the Photoshop of web development -- way too bloated. I realized that all the features I expected from PyCharm exist only in the professional version so now I've got myself a copy of that.

huhu
Feb 24, 2006

flosofl posted:

It's got a full featured debugger if that's what you're asking. Also has an integrated terminal and python console.

I guess to rephrase my question... In Python IDLE, I can run test.py, and then play around with it after.

test.py
code:
x = 5
code:
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
>>> x
5
>>> x+5
10
>>>
Is this possible in PycHarm?

huhu
Feb 24, 2006
I've been using PyCharm for awhile now I'm just not sure how to phrase my question in Google so I'm asking here.

vikingstrike posted:

Highlight code, right click, execute selection in console.

I highlight the entire file and do this and it gives errors.

Edit: Found it
http://stackoverflow.com/questions/21516027/running-code-in-pycharms-console

huhu fucked around with this message at 21:53 on Apr 27, 2017

huhu
Feb 24, 2006
I'm having a Pycharm or Python issue...
code:
from foo import bar

def test(input):
    myBar = bar()
    return myBar.myMethod(input)

AttributeError: 'bar' object has no attribute 'myMethod'
If I click on myMethod() and navigate to where it is originally declared, it opens the file foo and goes to the bar definition. What am I missing here?

Edit: It's a Pycharm issue. I renamed the directory and reopened it in Pycharm and it's working now. Any ideas what I might triggered by renaming the directory?

huhu fucked around with this message at 16:18 on May 1, 2017

huhu
Feb 24, 2006

NtotheTC posted:

Was the file actually named "foo" and the class "bar"? If not its possible you named your file something that was already taken by standard lib or an external library. Is the file in the same directory as the file you're importing into? Try
code:
from .foo import bar

Somehow between yesterday and today, and renaming the folder back to its original name, the issue is gone. This is good to know for next time though.

huhu
Feb 24, 2006
Anyone have any good resources for getting started using extensions (C/C++) with Python? I'm taking over a script that uses this and the most complicated C++ I've written has been for Arduino so I'm not really sure what I'm doing.

huhu
Feb 24, 2006

HardDiskD posted:

The liquor store?

Is it that confusing?

huhu
Feb 24, 2006
code:
temp/
	target1/
		/x
			file1.txt
			file2.txt
		/y
			file1.txt
			file2.txt
	target2/
		...
code:
rootPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'temp')
targets = [target for target in os.listdir(rootPath) if os.path.isdir(os.path.join(rootPath, target))]
for target in targets:
    xPath = os.path.join(rootPath, target, "x")
    xFile = os.listdir(xPath)[0]
    with open(os.path.join(xPath, xFile) "r") as f:
        for line in f:
            print(line) # Whatever commands I'd actually need to do with this line here. 
Is there a cleaner way to not have so many os.path.join() or would that require knowing the operating system I'm working with?

huhu
Feb 24, 2006
I would like to debug JavaScript inside a PyCharm for Flask projects. I see that I can set breakpoints in the JS code but PyCharm always skips over them. The only tutorial I can find online involves debugging static HTML and not Jinja2 templates.

huhu
Feb 24, 2006

Thermopyle posted:

I haven't debugged JS in a jetbrains IDE in years, but I seem to recall it was easier if I used an external js file included in my templates via a script tag.

I might be explaining this poorly. Here's my structure:

app/templates/input.html:
code:
<button>Do some JS from input.js</button>
...
<script src="{{url_for('baseViews.appstatic', filename='scripts/input.js')}}"></script>
...
app/static/scripts/input.js:
code:
// Code here for <button>
When I set a breakpoint in input.js for code related to <button> and then click it, the breakpoints are ignored.

Edit: The settings I think are relevent:

huhu fucked around with this message at 16:26 on May 30, 2017

huhu
Feb 24, 2006

Thermopyle posted:

This is a weird thing to say, so just to make sure you didn't accidentally type the wrong thing...you know that PyCharm is an IDE and Anaconda is a package manager?

I could see Pycharm being overwhelming if you've never programmed before. Perhaps better to start off with something more familiar feeling first like Sublime Text. That being said, I moved from Sublime to Pycharm in my learning progression and never plan to go back.

huhu
Feb 24, 2006
What would be the best way to take:

[{u'amt': 10.0}, {u'amt': 0.1}, {u'amt': 1.0}, {u'amt': 3.0}, {u'amt': 5.0}]

and turn it into

[10.0, 0.1, 1.0, 3.0, 5.0]

edit, think I found a good way:

values = [value for singleDict in dictlist for value in dict.values()]

huhu fucked around with this message at 15:50 on Jun 14, 2017

huhu
Feb 24, 2006
I'm reading up on Breadth First Search and this is the implementation the video I'm watching talks about :

code:
class Node(object):
    def __init__(self, name):
        self.name = name
        self.adjacencyList = []
        self.visited = False
        self.predecessor = None

class BreadthFirstSearch(object):
    def bfs(self, startNode):
        queue = []
        queue.append(startNode)
        startNode.visited = True

        while queue:
            actualNode = queue.pop(0)
            print("{}".format(actualNode.name))

            for n in actualNode.adjacencyList:
                if not n.visited:
                    n.visited = True
                    queue.append(n)

node1 = Node("A")
node2 = Node("B")
node3 = Node("C")

node1.adjacencyList.append(node2)
node1.adjacencyList.append(node3)

bfs = BreadthFirstSearch()
bfs.bfs(node1)
I feel like this is missing a part about where if X.adjacencyList.append(Y), then Y.adjacencyList.append(X) should also happen automatically. Because if you only did the first part, and tried to call BreathFirstSearch on Y, you wouldn't get X. Is that how it should be done?

Edit:

I'm thinking this would be good:
code:
    def appendNode(self, node):
        self.adjacencyList.append(node)
        node.adjacencyList.append(self)

huhu fucked around with this message at 15:13 on Jun 16, 2017

huhu
Feb 24, 2006
Does anyone have a suggestion for a tutorial that walks through the basics of sockets up to putting it on a server and being able to type in "huhu.com/index.html" and get a page to load? I've got something basic running locally but would like to explore sockets, wsgi, and related topics more in depth.

huhu
Feb 24, 2006
I've been using a script for a while now to launch my flask apps in debug mode.
code:
application.run(host=HOST, port=PORT, debug=True)
All of a sudden I started getting the following error:
code:
  File "C:\Python27\lib\logging\handlers.py", line 77, in emit
    self.doRollover()
  File "C:\Python27\lib\logging\handlers.py", line 350, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
Logged from file perfTimer.py, line 29
I eventually stumbled upon this solution:

quote:

I got the same error while developing a flask application. To solve the problem, I had to change the environmental variable from "FLASK_DEBUG=1" to "FLASK_DEBUG=0". The reason being that turning debugging on leads to threading errors. I got the solution after reading this blog

Where "this blog" points to http://azaleasays.com/2014/05/01/django-logging-with-rotatingfilehandler-error/ Any ideas what might have triggered this error to start popping up?

huhu
Feb 24, 2006

Loezi posted:

What's the easiest library to make a GUI with, given that I require hassle-free licensing (which rules out PyQt)?

Native elements are appreciated but not necessarily required.

Flask is also very nice.

huhu
Feb 24, 2006
Edit: nevermind.

huhu
Feb 24, 2006
I'm looking to start a pretty large Python project with the hopes of actually releasing it. The last time I tried this I failed pretty badly and have learned a bit but would love any suggestions before jumping in again. My thoughts thus far are to try and diagram the entire project, use a virtualenv, and document everything as best I can as I go. Any other suggestions?

huhu
Feb 24, 2006

creatine posted:

Does anybody know of a python3 module that let's you work with .FCS files? All the ones I can find are 2.7 only

Perhaps you could do a .FCS -> .txt with another tool and go from there? If .FCS doesn't have formatting, you could probably just do with open -

http://www.pythonforbeginners.com/files/with-statement-in-python

huhu
Feb 24, 2006

Hughmoris posted:

What Python books (if any) do you all have? I'm thinking about picking up Fluent Python and Effective Python.

Are you just starting out? Automate the Boring stuff is a great starting point.

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006
Trying to build a basic website with Django or Flask is a good way to get into backend/full stack development if you're interested in that kind of thing. When you can hookup the stuff you build with Python to a website - a whole world of awesome possibilities opens up.

For Flask I recommend this tutorial -
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
And the accompanying book.

For Django I'd recommend -
https://docs.djangoproject.com/en/1.11/intro/

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