I handle pretty much all of the programming tasks for my research group. The other researchers know some matlab and that was what everything was written in before I showed up. I prefer python much more than matlab so I've converted everything to python and flask web apps.
Flask is very simple. You can use Miguel Grinberg's Mega Tutorial if you've never done any web dev. If you know the basics of MVC, then Flask should take an hour to become comfortable with.
Couple tips:
overall i like the design man, pretty good looking site you have there
A web framework is a box of tools designed to help with building websites that are dynamic (not just a bunch of static text files).
Web frameworks are common in many languages (Perl has Catalyst, Ruby has Rails, Java has Spring MVC, etc). Python also has another web framework called flask.
Construction is used as a metaphor for software tools. A basic construction tool box includes things like: hammers, nails, screwdrivers, a rule/level, and saws.
You could construct a building without any of the above tools, but you may spend a large amount of time making tools in order to construct your building. Likewise you can construct a website without a framework, but you may spend time making tools instead of building the website.
Web frameworks can be overkill if you are making a very simple website with only a couple of pages that isn't updated very frequently. If you are creating a website that will be large, interactive, or needs to communicate with services a framework makes it easier.
Django is a big tool box to build websites in Python. You have components like:
Python the language -- you can write modules in Python that can be called in Django to produce output that is then formatted in HTML.
ORM (object-relational mapper) -- This layer maps out a correspondence between columns and rows in a database (like SQLite, MySQL, or PostreSQL) and a data object in Python. This allows you to read and write data from a database without knowing much about SQL.
Templating -- This tool allows you to create dynamic pages without needing to know a lot of Python or HTML. This is useful especially if responsibilities of creating and maintaining the website is split between development (done by programmers) and creative (editors/writers) tasks.
There are other tools in Django but the above gives you an example of things in Django that people find useful.
app.run
is
colors
sounds like something that shouldn't be in your back-end code.global
unnecessarily.global
to modify a global variable is always a bad and begs for bugs. More on that below.render_template("login.html",lform = lform, #...
should become render_template("login.html", lform=lform, # ..
from werkzeug.security import generate_password_hash, check_password_hash
if choice1 != "":
with if choice1:
because ''
is considered falsy. Same with if i != None:
→ if i:
load_user
actually fetch a User instance from Mongo? Wait a minute...You are grossly misusing global variables. Global variables exist once per instance running. Basically that means if you run your app somewhere (basic setup) only one user will be logged in at a time globally and if somebody else opens your app in their browser, they will be "logged in" as that other user.
You need to put all that temporary data in your session and implement load_user
properly. At that point you can use flask_login.current_user
to get the currently logged in user.
I think you'll have some more questions so just shoot.
Right, your first problem is that you cannot create an iOS app using either C++ or Java, unfortunately. You must use Objective-C or Swift to write the code natively, or you can use a framework to write code that works on both platforms. Options for this would be:
If you search for any of those, you should be able to see which one suits you best.
To make the leaderboard, you would need some sort of host, and you'd need to make some sort of web app or API. You could use something like Flask (Python), Ruby on Rails or even Spring REST (Java) to make an API that your app could communicate with.
The app would send the size of the fish caught to the web app, which would save it in a database. You could then use a database query to sort the sizes in descending order (the SQL might be something like SELECT (name, size) FROM leaderboard ORDER BY size ASC
). It would then return these to the phone app, which would render the leaderboard.
I don't think that will happen anytime soon. Flask depends on werkzeug and Jinja2 and that is a good thing. Bottle has a strict "no dependencies" policy and that is a good thing, too. Both frameworks have their right to exist.
But fear not, I am working on a plugin for Bottle that adds support for werkzeugs Request/Response objects and exceptions and integrates the interactive debugger. Jinja2 is supported anyway, so, with that plugin, you could turn Bottle into Flask quite easily.
Edit: I am Marcel :)
Hey, mitsuhiko.
Firstly, awesome work on Flask. I love that you can use it for tiny apps or legitimate sites, and it's very easy to get into.
My problem is with Blueprints. The documentation of them is rather limited in actual examples of what they're for. I understand how to create them, but the documentation is lacking as to why I would. Are they like Django apps where you can separate your site code based on functionality? I tend to learn best when I have real-world examples, and Blueprints are one of the things about Flask that I haven't been able to really "get".
I've also been trying to figure out a good way to structure larger projects. I think if there was one thing I'd like to see, it would be an example project structure with multiple blueprints and an app.
Thanks for all your hard work with Flask and its extensions!
Use a proper production server. See deployment options.
Serve your static content by a static file server, not the flask app. You could also opt for something like s3 storage.
You may even be able to go serverless with Zappa.
Points you could improve:
<path:path>
doesn't do what you think it does. It's not meant for complete URLs. short
function should create DB entries after a HTTP POST, not a GET (methods=['POST']
).'%r' % self.id
) is old.app.run
is only for local development and nothing else. Also it's deprecated and should be replaced with the Flask CLI method.db.Column
can have a default parameter and I don't see a reason why views should be nullable: views = db.Column(db.Integer, default=0)
-- shorted_redirect_url = Short(path=path)
os.env
or <code>app.config.from_envvar</code>)requirements.txt
file.Sorry to be so "brutal" but if you have any questions about any of these points, just shoot :).
I'm really not a fan of Flask or its API. I'm sure it makes for great hello world examples, but the conscious decision to expose request state through thread-local imports is just nasty.
It's a pointless hack when you simply could just pass a request object to the view callable. It also encourages unnecessary coupling to Flask outside the view code.
For anybody interested in a lightweight Python web framework without cutesy little hacks, I would encourage you to check out Pyramid. It's like Flask's big brother.
Oh, where do I start? ;)
So, the language you should probably learn is Python. Many people learn Python by building Django or Flask applications, that's a matter of taste. I personally think they are both nice, but Flask is easier to learn since it's not as complex as Django.
I generally use Python for building web apps, but to me Go is attractive because the language and the HTTP server in the standard library are extremely fast (compared to Python, anyways). You get non-blocking IO (like Node.js) without having to think about callbacks because each HTTP request is handled by it's own goroutine.
You can learn the language and be productive in a weekend. It's easy to deploy a web application in Go because the compiler produces a static binary and there's no WSGI server or anything else to worry about.
The downsides:
The default "web framework" in the standard library (net/http
) is extremely low level, much lower level than something like Flask. You'll probably need to pick a third party framework or a bunch of small libraries that build on net/http
, but there's no obvious answers.
If you're interacting with relational databases, you won't find anything like SQLAlchemy or Django's ORM. There's some ORM-like things, but I haven't seen any that cleanly handles the mapping of relationships between tables.
The built-in template language is somewhat awkward to use when it comes to template inheritance, although I think they're going to fix this in 1.4.
So basically, speed and the simplicity of the language make it appealing. It also has very low memory usage compared to the JVM, and you don't even have to deal with the JVM, which is ideal for me since it seems extremely complex. I don't know of any "websites" using Go, it seems to be used more for JSON API's and stuff.
I would create a custom filter and use <code>str.format</code>.
>>> '{:0>6.2f}'.format(22.21999999) '022.22'
0>6
means "make the resulting string six characters long, align to the right and fill with zeroes".2
means "round to two decimal places"f
means "display the number as a float (and not something like 2.2e+01)"Have you read flask's deployment options[1]?
> While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time.
Are you familiar with backend programming at all? If not, you might want to familiarize yourself with some kind of lightweight non-Rust web framework like Flask first.
Reason being, the Rust web libraries (like all Rust libraries) are relatively new so you probably won't find good resources aiming to teach server-side development from scratch using Rust - they will assume that you basically know what you are doing, focusing more specifically on the Rust stuff.
That said, take a look at Are we web yet. It has a good overview of the state of web development in Rust, which should give you some places to start, particularly the web frameworks section.
Flask has the code inside requests isolated from one another generally. You should read this section to get a better understanding of how Flask separates data between requests: http://flask.pocoo.org/docs/0.10/quickstart/#context-locals
The main worry with race conditions such as this is when dealing with 3rd party sources, such as a database. As they might both attempt to write the same data to a database (and only one record should exist), you should put safeguards in place such as locks, unique constraints, or similar checks.
The code inside the request / view function itself is not in danger of suddenly overlapping data-wise between the requests.
Do you have a specific case in mind?
I recommend Flask
You can start with this tutorial: http://flask.pocoo.org/docs/1.0/tutorial/
Another tutorial: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
The first tutorial should be enough to get started but the second link is also helpful
So almost just like Flask's? I'm alright with that, as long as it's robust and extensible (accepting user-defined converters). I love regex, but it's entirely unnecessary for almost any URL path.
The email verification/email alerts is missing, but my goto project for this is cookiecutter-flask.
manage.py
script.Blueprints <http://flask.pocoo.org/docs/blueprints/>
_ and Application Factory <http://flask.pocoo.org/docs/patterns/appfactories/>
_ patternsIt also has a basic registration script, but you'll have to add in email verification. If you do, then you should do a pull request back to the main project.
Programmer here. I use Django at my full-time job and for a bunch of side projects. I love it and it's great.
That said, I don't think it's a good place to start. If you don't already know Python, Django is going to be very, very confusing and it will seem like there's a lot of magic happening. Once you've got a bit of experience Django is great, but I wouldn't recommend it for beginners.
I've never used Pylons, but from what I hear it's more of a "put together your own framework" kind of framework. That's great if you're experienced and know what you want, but bad if you just want to play around and get some real results.
My advice for you would be:
There are plenty of similarities in the semantics of the language, and really if you were to switch to any other language from PHP, Python would probably be the easiest. There are certainly some important differences, however.
Instead of PHP's "array" you have lists (for an ordered sequence of items, which can be accessed via a numerical index) and dictionaries (a collection of items associated with identifiers). Dictionaries do not maintain the order of the elements added to them (unlike PHP's array, when used associatively).
Python will not coerce number types to a string when doing string concatenation, e.g.
num = 3 print("I have " + num + " apples")
Instead you need to convert the integer to a string:
print("I have " + str(num) + " apples")
Or alternatively use string formatting
This may seem annoying at first, but in PHP and other languages, implicit type coercion is often a source of subtle bugs.
Specifically pertaining to web development, you can't just dump a Python file in a directory on a server and navigate to it in your browser, you need to use some kind of WSGI framework. Python files also don't natively function as HTML templates (unlike PHP files), so for generating HTML you'll want some kind of templating system. Flask is a good choice to get up and running with both those things.
Dude you need blueprints. It's a big topic, so not something I could explain in a few lines - but definitely is how you should be structuring your app. Blueprints allow you to break your routes/app up into smaller, focused bits. You can also use your blueprint's class to contain the logic you don't want in your view handlers.
Most large websites (Netflix, Reddit, Lyft, Uber, Patreon, etc) all use some form of webframework that requires extensive coding (most of those utilizing "Flask"; a Python based framework. The days of WYSIWYG editors (Netscape Composer, Dreamweaver, etc) are essentially over. I would say there is more coding that goes on now days compared to days of old as browsers are more advanced and can allow for much more advanced intricacies, beautifications, and elaborate database setups.
On the other hand, you can deploy Wordpress or other high level webframeworks that require little or no coding to get a very basic website going.
I really like using them to 'register' functions. Flask is a great example that uses them for just this: http://flask.pocoo.org/
You 'decorate' functions with app.route('/url')
, so that whatever function you decorated, is called when that url is requested - lovely.
Here's an indication of how it works:
class FuncStore:
def init(self): self.funcs = []
def register(self, f): self.funcs.append(f) return f
fs = FuncStore()
@fs.register def my_func(): print("Mine!")
print(fs.funcs) # [<function my_func at 0x0000018D682A2E18>]
The other classic example is a 'timeit' style wrapper, that measures the time it takes to execute whatever it wrapped:
import time
def timed(f): def wrapped(*args, **kwargs): start = time.time() res = f(*args, **kwargs) stop = time.time() print("Execution took {} secs".format(stop - start)) return res return wrapped
@timed def long_thing(t): time.sleep(t) print("Slept for", t)
>>> long_thing(3) Slept for 3 Execution took 3.0013415813446045 secs
Jumping on top comment. Flask and Bottle are very easy to learn and get started with, while both being quite powerful.
I have used both of them near interchangeable as there are just a few idiosyncrasies. Bottle has the advantage of portability as it is literally a single file that can be included in your project. Flask however has a lot more plugin support and is considered a golden example of how python should be written. If you're just starting out and looking to learn, you really can't go wrong with either.
I'd recommend flask, Ive used it in all sorts of projects, from tiny crud front ends, to full-blown applications. Other points in flask favor (IMHO)
Sounds like you want Flask really.
You could do it with Django but IMO Flask is much easier to pick up as a newbie. In this case you don't need any of Django's extra features, and the structure will just slow you down. If you wanted to convert your app to Django later for a learning experience it'd be trivial too.
You could probably just read chapters 1-3 of this tutorial and know enough to write your app:
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
Also worth reading:
http://flask.pocoo.org/docs/1.0/quickstart/#quickstart
If you already have the functions written you could probably learn enough Flask to get your urls/templates written in a few hours from scratch.
flask.send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False)
> Sends the contents of a file to the client. This will use the most efficient method available and configured.
I'd follow a tutorial so you can see and feel how the framework is used, and then I'd tackle user uploads and downloads.
Flask-Upload, a third party extension for file uploads.
To add to this, Armin very carefully documented the implications of running with the debugger in production.
From the quick start:
> Attention > > Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on production servers), it still allows the execution of arbitrary code. This makes it a major security risk and therefore it must never be used on production machines.
And from the section on the debugger:
> You can use Flask’s builtin development server with debug=True on your production host, which is helpful in catching configuration issues, but be sure to do this temporarily in a controlled environment. Do not run in production with debug=True.
There isn't even a stretch where you can blame Werkzeug here.
It was so much worse than just an open test site, though. It was basically a public-facing Python console hosted on the root of the domain. Remote execution without even having to do anything because some sysadmin didn't read the fucking manual.
If I were you, I would just develop a "web app" that would run the python script (on some server) once the two ID numbers are submitted. and then just spit out the results on to the webpage. That way the script will work anywhere as long as your co worker is using a web browser. This will be fairly simple to implement using Flask.
(only if your co-workers don't want to mess around with the terminal. And I also think developing a GUI would be fairly complicated for something as simple as this.)
Generally it's recommended to run flask apps in a WSGI appserver of some kind. See the flask docs for some of them and their instructions.
These appservers have functions to handle scenarios where your code dies.
Personally I use uWSGI in emperor/vassals mode for productive servers with several different apps running at the same time.
A vote for Flask here. It runs its own web server for development (defaults to port 5000, easy to make it run on a wsgi compliant server like apache with mod_wsgi), it's lightweight, but has plenty of useful bits already included, and it doesn't abstract your database interaction. If you want to go with MySQL, you can use existing documents for the MySQLdb module (or any MySQL module). The website has great tutorials and docs, and it doesn't lock you in to a certain way of doing things like Django and other 'big' frameworks.
You are going to get every single framework mentioned in this thread so the best way is just to simply try each one (or the best candidates) a little bit and figure out which one suits you best.
I have tried many frameworks and found Flask to be amazing. I highly recommend it.
3 easy solutions depending on what you work and with what. For all of them, you have to use generator (flask stream) to stream data.
- If you run an external command in your python script : a solution here.
- If your logs are in a file, you can use SSE to stream your data. You just have to open your file in your generator and **yield** "data:" + lines + "\n\n" in a loop.
- You can use websocket, but I would say : it's easier to stream text through SSE instead of Websocket. It seems that Websocket are not supported by Nginx Unit for example.
Not sure if you are aware, but there is already a project called flask which is a python web microframework and is quite well established. Might want to consider a different name to avoid confusion (and help with SEO)?
It depends on what you are trying to make. I for myself can only recommend Flask. Its very easy for beginners and very easy to extend its functionality beyond what the core provides. Flask is more than enough for small to medium sized projects. It definetly is easier to learn. You can take a look here: http://flask.pocoo.org/ - some more information with more tutorials is also availabe at /r/flask
I agree, and from what you said, it might be easier to start using something like Flask or Bottle, to learn alternative or less automated ways to do the kinds of things that Django does. That would make Django much less mysterious, I think.
For example, URL routing, templates, etc. will be easier to understand in those micro-frameworks.
> I want my URLs to be organized like GAE, web.py and Tornado.
http://flask.pocoo.org/docs/patterns/lazyloading/
> I want my URLs to be mapped to their own classes like GAE, web.py and Tornado.
http://flask.pocoo.org/docs/views/
> If all of these are possible with Flask then ignore this comment :)
Nothing ever gets ignored :)
> Note, because Flask is a microframework, it doesn't include some of the features of full-stack frameworks like Django and web2py, such as an ORM, a forms system, and an authentication system.
However there are tons of extensions for exactly these purposes: http://flask.pocoo.org/extensions/
You can use flask variable rule routing, some examples found here http://flask.pocoo.org/docs/1.0/quickstart/#variable-rules
e.g.
@app.route("/garage/<car_number>", methods = ["GET"]) def get_car_info(car_number): return car_number
When you construct the url with url_for
you can pass in variables as keyword arguments.
Hello,
What about reading docs my friend?
http://flask.pocoo.org/docs/1.0/tutorial/deploy/
It isn't that hard. You just need a server with python installed and configured.
Absolutely. Reddit itself is coded with python. What you will want is a web framework which makes the web app portion of development much simpler and easier for you. One of the most popular and simpler web frameworks for python is called Flask. You can find some easy Flask tutorials just by googling "Flask tutorial."
Storing credentials in plaintext in the DB is not a great idea. A file on the web server or environment variables may be a better way to go.
Flask's config object is probably what you want. http://flask.pocoo.org/docs/0.12/config/
I store credentials for the APIs I need to hit in environment variables and I have Flask pull them into the config when the app starts up.
I had a similar question once, and I used this framework: Flask Very easy to define your REST API and work with sql database. It uses python, which is fairly popular, although you might want to check which languages are in use near you. If you want more used solution, Django is your choice, but I'd argue it's an overkill for your use case. You could try some Kotlin backend, like suggested, but it's not in high demand right now at least where I live.
I believe you are confused by the app.run() method. That method only starts the local development server and nothing more. However when you are deploying with wsgi that's exactly what you want to avoid. What you want to do is "wrap" your flask application within a wsgi container which is then executed. If you want. wsgi container becomes the application server just like app.run().
I do not know of your exact setup, but here is an example from the flaks documentation to illustrate exactly that:
>from gevent.wsgi import WSGIServer >from yourapplication import app > >http_server = WSGIServer(('', 5000), app) >http_server.serve_forever()
As you can see, flask instance is imported and then used as an argument, app.run() is not called at all.
@edit: Noticed that you mentioned uwsgi and nginx combo. In that case have a look at the flask documentation example. It has a paragraph that states pretty clearly that one should put app.run() in either a separate file or after:
>if name == "main": > app.run()
That's in order to prevent app.run from running when that module is being imported by uwsgi. So in any case, when deploying a flask application, one must not include app.run().
Hope it helps!
Python is not PHP - you can't create simple file and run it on web server. In Python you have to use some Web Framework to run it on web server.
PHP lets you create shit in code - mix PHP, HTML, and SQL in one file. Python frameworks force you to use good solutions - learn good habits. And you don't have to write your own (unsafe) code because you can find better solutions in framework or in its extensions.
EDIT: start with flask - http://flask.pocoo.org/
He forgot to activate his virtualenv in that tutorial - from the docs( http://flask.pocoo.org/docs/0.11/deploying/mod_wsgi/ ):
Working with Virtual Environments
Virtual environments have the advantage that they never install the required dependencies system wide so you have a better control over what is used where. If you want to use a virtual environment with mod_wsgi you have to modify your .wsgi file slightly.
Add the following lines to the top of your .wsgi file:
activate_this = '/path/to/env/bin/activate_this.py' execfile(activate_this, dict(file=activate_this))
For Python 3 add the following lines to the top of your .wsgi file:
activate_this = '/path/to/env/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(file=activate_this))
This sets up the load paths according to the settings of the virtual environment. Keep in mind that the path has to be absolute.
If you're using SQLAlchemy without prior experience in basic sql queries, I can see how you can get lost. As he recommended, start with sqlite.
You interact with a database by retrieving and inserting data so it helps to understand how to use SQL to make queries.
If you've not done the official Flask tutorial, I'd recommend to start there. It walks you through building a very simple app using sqlite as a database backend.
http://flask.pocoo.org/docs/0.10/tutorial/introduction/
(EDIT) Learning RDBMS is a whole different thing too but once you know SQL it's easier. Understanding normalization also helps later when designing your tables. Once you understand table relationships, SQLAlchemy may start making sense.
You should look into Celery. It integrates well with flask. I used it for a couple of projects and like it a lot.
Edit: Have a look at this sample which is pretty similar to what you are trying to do.
/u/krippler_ and /u/FifteenthPen each have provided parts of the solution. Put them together and you'll get what you need.
@app.route('/whatever') def whatever(): # do whatever and you have sometihng in name return render_template('whatever.html', name=name)
Then in your template file.
<html> <head></head> <body> {{ name }} </body> </html>
This will display name
in the template. You can enclose it in whatever tags you want. Flask has lots of good documentation and a super useful quickstart here. Your question is answered there. When in doubt, consult the docs.
You can try with checking Django - most popular python web-framework to start building web-apps and websites quickly. It has great documentation and it fully working with Python3. If you feel comfortable with Python and think, you can start like "from scratch", check Flask microframework and docs for it. It supports Python3 too.
If you don't know pick either Python or Java depending on if you prefer a dynamically or statically typed language. Especially when you quickly want to get started with a web app Python + Flask is very easy to pick up.
See http://flask.pocoo.org/docs/0.10/patterns/packages/#simple-packages
import db
import config
Those are implicit relative imports. They are not a good thing because imagine you have a global package named db
or config
. Things would break.
When all your code is inside a python package (let's assume it's named lsq
), you'd instead from lsq import db, config
to import those two modules (or from . import db, config
if you prefer explicit relative imports).
You do not have to merge them. You don't even have to know they are flask applications. You can compose arbitrary WSGI applications using the server configuration, if the server provides that feature or through another WSGI application as described in http://flask.pocoo.org/docs/patterns/appdispatch/
Flask might be a good back-end framework to start with, since you're already familiar with Python. I believe it was actually inspired by Sinatra, so it's a little less "magical" than Rails or Django. You'll basically be writing a set of request handlers that can return either HTML pages or JSON data, so you can get a sense for the backend's role in a web application.
I found bits and pieces of this tutorial useful: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
> Flask ... shares the same problems as CherryPy in that everything ( templating, ORM, etc ) is the responsibility of the developers.
huh? flask ships with jinja2 templates by default but you can plug different ones in.
If you're familiar with Python you may be interested in Flask, it's a lightweight framework for developing Python web applications and is able to generate web pages from templates, talk to databases and other such stuff you'd expect from a web framework. It's also well documented and comes with a good tutorial in the documentation pdf.
Once you've written your application you can deploy to a webserver like Apache or such for production use.
Would Python be a good language to use to implement this? Definitely. I personally prefer Flask. It's pretty well-documented. If you decide to use Flask, you're going to want to look into Flask-SQLAlchemy, a Flask extension for managing databases.
Flask. My favorite web development framework. It's tiny, but it's simple, easy to use, and a perfect for simple websites. Plus, it makes a great foundation that you can expand to build even large scale sites.
1) You can use atom as an IDE. Visual Studio Code and the community edition of pycharm are also good options.
2) for starters focus on creating routes. routes are endpoints that allow http requests to access underlying data. for example a GET /api/countries to get a list of countries or POST /api/countries to add a new country. this only requires knowledge in data structures (lists & dictionaries), http methods GET and POST, the json library, flask views/routes. once you understand that tack on defining and accessing a data base like sqlite. after that learn how to use jinja templates so you have an interface to ingest data/params via forms and output it into a webpage with html and css.
3) a little dated but all of the essentials of a flask rest api simplified: https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask here's a fun ds project using flask https://realpython.com/lyricize-a-flask-app-to-create-lyrics-using-markov-chains/ and of course the flask tutorial itself is great http://flask.pocoo.org/docs/1.0/tutorial/ hope that helps!
Well you can pass keyword arguments into the view function with <code>url_for</code>.
return redirect(url_for('my_view_func', q='fizz', v='buzz'))
> Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments
Maybe you could use context processors and pass in a function capable of dynamically building the html markup for your Twitter based on the tweet data. See http://flask.pocoo.org/docs/1.0/templating/#context-processors. Maybe you could even call render template from within that function. I'm not sure if itll work cause I haven't really used flask templates (mostly for apis), but do tell me what comes out of it should you go down this route :D
Python is not used for web interfaces, as that would require web browsers to support python. They mostly support HTML and JavaScript, so you would have to use those for the interface itself.
Python can be used for the back-end. Flask would be a good choice, for that.
Basically, use HTML to generate a webpage, javascript to make it interactive (e.g. print new chat messages from, or send commands to your Flask back-end), and a back-end to call the bot itself.
HTML+JS is called the front-end (running in a browser), Flask (or other technologies, apache, PHP, NodeJS, etc.) on a server is the back-end, and front-end+back-end is called full-stack.
Flask is easy
Step 1: http://flask.pocoo.org/docs/0.12/quickstart/
Step 2: http://flask.pocoo.org/docs/0.12/tutorial/
You can get started with minimal amount of python but if you want to build more complicated programs than you need a better understanding of the language.
My feeling is that for someone new to programming web apps, jumping right into websockets and pubsub and streaming is a big step. If you just want to update data on the webpage without refresh, why not start with jquery and ajax? Jquery is not obsolete yet! The flask docs have an example you can try quickly (below). On the webpage you enter values, click a button, and instead of submitting, jquery send the values to the server, with a callback function. A server-side end point function calculates, then returns the result to the browser callback for display. if this concept works for you, there are tons more examples online.
http://flask.pocoo.org/docs/0.12/patterns/jquery/
Please check the documentation:
> To access parameters submitted in the URL (?key=value
) you can use the args attribute:
> searchword = request.args.get('key', '')
> We recommend accessing URL parameters with get or by catching the KeyError because users might change the URL and presenting them a 400 bad request page in that case is not user friendly.
UPDATE If that doesn't work, use the browser's network inspector to see what it actually sends. You should also see that in the logs of Flask's development server.
You said you were using curl
to make the POST
requests to your Flask app, thats why I asked what curl
command you were using.
If you're trying to use your Flask app in the browser, you'll need to add a page with a form in it with a text field for the zip code; the quickstart guide "Rendering templates" and "Accessing Request Data" sections talk about how to add a template and view to submit data from a form.
Flask will serve your needs well. It'll help you handle the logic and structure of serving the pages and still works inside of python so you can write your backend python game code to interface with your web pages. The microblog tutorial from flask's website will be a very good intro. You can do this tutorial in an hour or two and learn a ton about flask.
Note: If I'm understanding correctly, you don't really need flask for such a task, but it's going to make your life a lot easier.
You don't need app in your blueprint and ORM
Import db and blueprint where you create your app, and then 'register' the blueprint and db.
Take a look at this: Application Factories
Dude, here are two libraries in Flask ecosystem that when used together can do exactly what I was talking about:
Using those in a Flask project you can create a websocket server that uses redis as its IPC. I'm not fucking with you. What he said isn't completely crazy, this is the type of shit I work on every day at work. You're judging a guy's entire knowledge by one sentence you read from him on a random linux IRC channel. Maybe stop being a douchbag?
I would not use PHP. For anything. If you want to use Python, I would suggest you use Flask instead. A common approach is to let Flask serve the page through either Apache or Nginx.
This article is a bit old, but it should point you in the right direction:
http://vladikk.com/2013/09/12/serving-flask-with-nginx-on-ubuntu/
Here's Flask's documentation:
Disclaimer: I used PHP for years. I can't recommend anyone to touch it with a stick.
My anecdotal experience suggests that django works great for full end to end solutions--databases, accounts, authentication, session stores, cookie management, etc.
It sounds to me that what you're looking for may serve as more of a frontend for a script. Django would definitely work but may have more than you need.
I'd check out tornado or flask, which may be easier to get started with.
If you do choose to go with django, you probably already know how fantastic the django documentation is. You should reference these a lot. There's also a healthy ecosystem of apps for django that serve different purposes you may be looking for.
> I guess what I'm asking is can I buy a design from Themeforest and modify it to work with flask?
Why can't you? That's what the templates and static folders are for. It's just HTML and CSS and nothing to do with how flask work. It'd make a poor web framework if it doesn't work with HTML and CSS.
If you need dynamic data that Flask needs to provide then you modify the templates with Jinja code.
(EDIT) Check out the Flaskr tutorial from the Flask docs to see how to add CSS and HTML to your Flask app. http://flask.pocoo.org/docs/0.10/tutorial/introduction/
> I didn't do anything web-based...
Step one is to learn HTML / CSS and build a few websites by hand.
Once you have a good handle on that, look into flask. Don't skip step one, flask will not make much sense without an HTML background.
If you were familiar with Flask, I would recommend just making a button which links to a function in your Flask app.
Since you're probably not using Flask (though, you should; It's a totally Python-based web framework which its more lightweight than Django!), your best bet is to use PHP to call an OS command. It's not super secure, but it'll work for your purposes. More info
That's about the only way to do it. Seriously, though, I highly recommend using Flask for a Raspberry Pi-based web server. Not only does it give you a nice, easy-to-understand web and templating framework, it also lets you run Python code EASILY from a webpage.
Just use a standalone web server, such as http://flask.pocoo.org/.
I assume you will serve your app to a restricted set of users on a private network, and I will not discuss the security implications of such a thing.
But you can go with something as simple as:
from subprocess import check_output
from flask import Flask app = Flask(name)
@app.route("/") def hello(): return "Hello World!"
@app.route('/ls/<path:path>') def ls( path ): return check_output( [ '/bin/ls', '/' + path ] ), 200, {'Content-Type': 'text/plain; charset=utf-8'}
if name == "main": app.run( debug = True )
Accessing
http://localhost:5000/ls/usr/bin
will give you an ls of your /usr/bin directory…
As I said, be very careful to security implications of such a thing!
The absolute most simple way is to subclass BaseHttpServer and that will work for trivial applications with a very small load. However usually web programming in Python is done via WSGI, which is like the way a web server like Apache hands off a request to another application (like something written in Python). There are a few WSGI frameworks for making this relatively easy - check out Flask for a simple and powerful example.
I really wanted to use Pyramid, but the last time I looked at it I was surprised how few plugins exist for it.
Look at flasks: http://flask.pocoo.org/extensions/
Can you ELI5 what Pyramid has for it that is not in Flask?
Really not a good article.
Referring to Django when talking about "more advanced tools" sounds really odd to me. As someone who started out with Flask ~2 years ago and now working full-time with Django I have yet to see something that I like better in Django. Flask is just more flexible and thus more powerful in my eyes. And it has a superior templating engine.
Then the whole article starts with a false statement/assumption:
> The syntax for those URL patterns is not very advanced: parameters can only be captured as path segments rather than arbitrary groups within a regular expression.
Wrong. The author probably didn't know how easy it is to add custom converters. And that makes the whole article kinda pointless.
But I don't think what he did was the best approach anyway.
Flaskr project is for creating a simple blogging app. http://flask.pocoo.org/docs/tutorial/introduction/
Pyramid's blogr is comparable: http://pyramid-blogr.readthedocs.org/en/latest/
Going through both should provide a really nice contrast.
Don't know of comparable Django project- someone else may
> is python an acceptable way to create websites?
Yes.
>I've used it for scripting before but not sure of its effectiveness in front end stuff.
You don't actually use python in front end stuff, you use HTML/CSS/JS for that, python is better suited for back end stuff.
>I guess there needs to be a language on top to translate python code to html etc?
Not really, but close. You use templates mostly, like Jinja2 for example: http://jinja.pocoo.org/docs/
Basically python returns HTML code/text to your browser which then renders it.
>guess you'd need a gui editor?
Eh, you could use something like that, although I just use text editor. Most of my html templates I edit in pycharm.
>How complex would this be to achieve and does anyone recommend any guides or links?
Not complex at all, assuming you know python basics after finishing few tutorials for web development you should be able to make this.
As far as resources goes, check out the flask documentation http://flask.pocoo.org/docs/quickstart/ it should be fairly simple to understand.
About halfway through Learn Python The Hard Way, I started playing around with Django.
At that point, I never felt like it was lack of understanding of Python that was holding me back from understanding Django, it was much more challenging to digest all the infrastructure stuff, as /u/legrandin pointed out.
Personally, I found the Django tutorial really frustrating, but that could just be me. I abandoned Django, worked with Flask for a while, and then came back to Django and it made a lot more sense. But whatever works for you...
If you need a lightweight server you can use a microframework like Flask. Unless you really need raw sockets for some reason, going lower-level than that doesn't usually give you anything.
Django is where you should start if you're a beginner. You do not need Python 3 compatibility.
There are many frameworks because there are many different opinionated people who were not satisfied with what they were offered with. Once you get experienced with web development, you might find out that you do not need scaffolding, object-relational mapper, internationalization, templating, any feature that comes with Django or that you need something different for your specific project. You might find that these features are actually getting in your way instead of helping you out. Once you get there, you might want to start with something small, like Flask, that offers things you know you will need and build on top of it.
I hope this help.
You would likely want to turn your program into a web server REST API with something like Flask. Then this could be requested from the browser to execute your Python code and return the answer. But if your goal is to just make this functionality accessible on the web, it's probably better to rewrite it in JavaScript so it can be run in the user's browser.
> I've spoken countless of devs who didn't get the implications of not setting your secret key to something which is actually secret
Those countless of devs are really bad at their job, if they can't read documentation at all:
http://flask.pocoo.org/docs/1.0/quickstart/#sessions
It's mentioned in the first paragraph, the second paragraph and the comment for the third line of code. And here, in the API documentation:
http://flask.pocoo.org/docs/1.0/api/#sessions
It is literally in the first line.
How on earth do you miss this?
I actually switched from learning Flask to Tornado myself. Too much context-locals magic happening under the hood with werkzeurg for me to be totally comfortable with it. (Plus Tornado comes with a pretty good plain template renderer out of the box, without requiring Jinja2 (although nothing stops you from using Jinja2)).
Django has wayyy too much stuff abstracted for my liking. I never needed WTForms or anything for that since parsing request.arguments
is easy enough to do already...
Anyway, I stick to the basic structure of:
./app controllers/ model/ static/ templates/ init.py config.py main.py routes.py utils.py
main.py
contains the application bootstrapping code. "global" functions live in utils.
I use routes.py since in Tornado, the default way of routing is via a tuple of a ('path-regex-pattern', ControllerMethod)
tuple. The Flask equivalent would be using <code>add_url_rule()</code>. Therefore routes imports the controllers.
Controllers import models. Generally 1 controller per .py. In Tornado, all controllers eventually inherit from tornado.web.RequestHandler
. I generally write a BaseHandler that does all of the housekeeping (like auth, wiring up models, etc.) and children controllers inherit from that to access the housekept instance members (like the model). In Flask default function-based controllers you can do this with multiple decorators where your base handler acts as the child handler factory.
Think about flask in terms of a server and client architecture. You're using the HTTP and HTTPS protocols to communicate between the client (user's browser), and the server(flask). When a user presses the submit button in a form, it will send a request to the server. By default, this request is a GET request. You can also have it send the data in a POST request.
GET requests basically just tack on the variables from the form to the end of the URL, while POST requests send data in the "background". Flask provides ways to access these variables depending on the request type.
While I also recommend the link /u/jaapz provided to provide more context, this link might give you a more immediate answer to your question.
What you're looking at is an example of the Application Factory Pattern
So instead of passing the app at the time of the extension's construction, he or she is passing it in a call to init_app
here (ignore the line immediately above, that's garbage that shouldn't be there)
> A Flask app that uses SQLAlchemy, but not Flask_SQLAlchemy,
Understandable, you keep your business/core logic independent from Flask.
> a mutable dict;
For your flask config seems like default flask behavior?
> and selectable SQLite in Jupyter Notebook... How do you feel about it?
Congrats!
> Electron app, with pure Javascript?.
yuck
Django can absolutely do this though it may be overkill. Check out the official Django tutorial or maybe even Flask.
Don't know if this is exactly what you're looking for, but here we go.
There's a <code>send_file</code> (and <code>send_from_directory</code>) which you can use to directly send files to the client without using a webpage.
To upload a file here's an excerpt from some code I have used before:
# Flask view on the server @route("/upload_data", methods=["POST"]) def upload_data(): f = request.files["file"] # f is a normal Python filedescriptor
# Script on a local computer with open(filename, "rb") as filehandle: requests.post("http://my-url.net/upload_data", files={"file": filehandle})
Then don't save it. You can parse the file by reading it from <code>request.files</code>.
The problem with StackOverflow and many other source you find by googling is that half the time they present you a solution without actually explaining it. I strongly suggest that when you read a tutorial or some answer on StackOverflow, you also read the API documentation about things. So for example when you read this line of code:
from flask import request
you go to http://flask.pocoo.org/docs/0.10/api/ and try to find it there. Then you follow the white rabbit until you know what request.files
is.
Is the SECRET_KEY configured properly on the heroku server as well?
That would be my first guess.
"In order to use sessions you have to set a secret key."
http://flask.pocoo.org/docs/0.12/quickstart/#sessions