#web-development
2 messages · Page 6 of 1
and if you want to know more about them - like what roles they have on which servers and so on - you'll need more than just the discord login
you'll need the bot to fetch all that info and push it over to a database that the site can access, cause the login won't give you much info at all.
@deep cave sorry for ping but could you suggest me any website or whatever to learn programming a website with Python?
actually I don't know any comprehensive tutorials for that. I will say though that both Django and Flask have pretty decent tutorials on their official pages.
they also have good docs
I do wish someone would make a comprehensive webdev with python course.. I've even considered making one myself.
my recommendation right now is, if you already know python, just to start with Flask and follow their quickstart
to get a basic website up and running
once you just get started you can learn one thing at a time from there. your learning can be motivated by actual needs, rather than arbitrarily dictated.
I'd do a Django one myself but I sound like a 2 year old Spanish baby girl with Chinese accent when I try to speak English
Adding OAuth to my project with Django wasn‘t that complicated, what‘s hard is using it for permissions
yeah
so i had to make a bunch of mixins that provide template tags like „is_member“ or return Forbidden when is_member = False and so on. I‘d probably prefer to just hook into Django‘s permission system but that‘s probably a bit more complicated
For a Django project.
I read about using Jinja2 instead of Django template engine. Before Django I used Flask, so I have some experience with Jinja2, but on every stackoverflow and quora thread, someone says "using logic in template is stupid", talking about pure python in templates with Jinja2. Why is it stupid ? I think my code is cleaner when I can call some functions from my templates, like datetime.now and things like that, instead of tweaking all the shit in my view in context processor, etc.
And if I use Jinja2, what can happen in long term ? Can I have some problem with using Jinja2 in Django?
there's actually a lot of stuff you can do in django templates
if you want to call e.g. datetime.now in django templates, there's a builtin for that
but I don't think that using the Django templating engine instead of Jinja will be too different
I think the general idea is you want to keep your logic and view layers modular
DateTime is a example.
My real problem is that I have some getshit(id) personnal functions that i want to call in my templates
like getstaffdepartement(52) that return a string "HR" for example.
Its only some read-only func.
Its my preference to do that, but in term of security, what can happen?
if you want to do something like that in your templates, you can write your own custom template tags in django - https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
I don't think it's an issue with security
the issue is your view layer now "knows" how your logic layer works, which it shouldn't have to
for a more in depth explanation of this idea see https://www.infoq.com/presentations/Simple-Made-Easy
I will look into all that. Thx for your answers @meager anchor @molten tide
Hello people. A question regarding emails - I've managed to send emails using smtplib and my email adress, this was achived via a simple script. What I actually want to do is to allow users to send files to me using a webpage as interface.
The site itself will have a form where the user can choose a file to attach, aswell as a couple of extra options.
So my question is - can this be done with smtplib? How would I handle the user's pw? (if it has to be handled at all) Or are there other ways to achieve this?
As always, excuse my english and my lack of expertise with python. Thank you all. = )
@winged ermine It can be done with smtplib, but you are probably better off having them upload it to the site with a form and storing it there - sending emails that way will probably end up with your email address being blacklisted
bot.tags["ask"]
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
I have this SurveyMonkey website that I want to create a Flask app out of
You want to build a survey site?
I wnt to replicate this website using Flask
Only a single page from that website
It's basically a survey only
It's not as trivial as you'd think
But it depends what level of professionalism you're going for
Whether you're storing personal details - you'd need a GDPR process if so
if you just have a form and want to store responses, that's fairly easy
maybe look into the flask docs themselves, as well as flask-wtf and some kind of storage backend - mysql, postgresql, rethinkdb, whatever you want
sqlite is no good for flask @ripe imp
you need to be running a bunch of flask worker processes, and the resulting issues are not that fun
I'll use MySQL then
I tend to prefer server-side
It's less processing, potentially less network traffic, and doesn't require the user to have JS enabled
I see, nice! :D
Are they called sql based? I have no idea but SQLite is pretty much enough for me and does it's job pretty good except not being able to filter some stuff
What would be the closest database that I can use? MySQL seems to be it but I wanted to ask you pros
Don't use SQLite for anything multi-process, that's the rule
Most websites you'll build will have multiple worker processes
so, no sqlite for you
I am not sure what workers are but if you are talking about that you can't write multiple items in it, yeah it is one of the reason that I'm gonna switch :D
Can't write multiple at the same time*
Well, basically
and this is especially true for things like flask
Most of the time, your webapp is single-threaded, without concurrency
so, you can only handle a single request at a time
therefore what most people do is spawn a set of worker processes
using, for example, gunicorn
that way, a bunch of instances of your webapp are running in parallell
this allows you to handle way more concurrent requests, but since sqlite is a purely file-backed database, you're going to have a lot of problems if you try to access it from multiple processes at once
realistically what you need is a database that comes with its own server
so, yes, mysql, postgresql, but also document-oriented databases such as rethinkdb, or key-value stores like redis
Hmm I don't know anything about the other structures so I'd like to go for a sql one
Which would be better, mysql or postgre?
postgres is generally considered the best sql database out there
the sql is different to what you may be used to
however
you often don't actually want to be writing sql anyway
I mean I'm hoping what I will use will have its own ORM(?) or whatever it is called that would let me write it in python :D
SQLAlchemy is the go-to ORM for relational databases
Like the SQLite used it django objects.get.filter blabla
document-oriented databases have no query language, and so no ORMs
you mostly just write python
Nice
rethinkdb is great at this
a document, by the way, is a mapping type
which is to say
a dict
however, on the other hoof, relational databases like MySQL and PostgreSQL are way, way more strict
in a sense, that makes them safer
I mean my data has a lot of relations with eachother like almost everything is either are a foreign key or a manytomany
you create your table, it has these fields, and they're those types
this field can only ever be a number
and it has to be present
this is the kind of validation you get from a relational database
and it's entirely built-in
if you try to insert data that doesn't match the schema for your table, you get a loud error
which can be great, since it's very obvious when you mess up
most document-based databases do not do this
you can give it whatever you want
it'll take it
now, some of them do allow you to specify a schema
in that case, it's an optional thing, but it's there if you need it
The loud errors is in the relational databases right?
I need that because I suck
xD
After all this I think I'm gonna go with postgre, thank you :D
Gotcha
What framework supports async well? Is aiohttp pretty much the only choice?
thanks! are there plans for Flask or Django to fully support async or is the effort infeasible?
not that i knew about
I need help making a table in html
A table of radio buttons
So far, I've used <input name='optradio'> to make the radio buttons optional (only single click)
I can now select only one button
Not from each row but the entire table, I can select only one radio button
But I want to be able to select one radio button from each row
So each row needs to have its own name
That name attribute can only work with input tags to create optional radio inputs
Different names like?
you solved it by putting a name on the inputs
each row of inputs
needs a unique name
I'm not sure how else to explain this to you :P
optradio is a predefined name that gives that property to radio buttons
Other names won't
I don't get your point
That is how you must solve this problem
If you need to generate the names dynamically, well, what's wrong with that?
you said it's a predefined name
Yes
it's only predefined in that it's in the generated html
there's no reason you can't generate the names using a template
or, heck, even js
I'm sorry I don't know how to do that
If you check the code, you'll see that I've
Created td elements for each radio button
And given optradio attribute for each
And that makes only one of radio buttons from the entire table (matrix) to be selected
Whereas I want for every row
I really can't think of a better way to explain the solution
Radio buttons with the same name act as a single group
So, clearly, you want each row to be a group
which means the radio buttons in each row need different names
But you see, optradio1 as a name won't work
Why?
CSS does not operate on names
It uses classes and IDs, mostly
It's just how HTML works?
The browser is doing that
There's no reason that that should be the case
I need to AFK, but that definitely works
@brave mantle Done! Thanks a lot man!!
Quick help: how to center the radio buttons in that table?
Center each radio button in its respective cell
align-self doesn't work
are you using grid / flexbox?
neither doesn't margin or padding
afaik align-self only works there
@meager anchor I'm using a normal HTML table
okay
well for nice alignment, i'd use something like flexbox or grid
they are CSS things that allow you to control the layout of your website
https://css-tricks.com/snippets/css/a-guide-to-flexbox/ and https://flexboxfroggy.com/ are really good
then you can give your the buttons nice alignment along the page, along with padding, responsiveness™ and more great stuff
Looking into it.. thanks 👍
note that flexbox is for one-dimensional layouts though, maybe grid is better suited for this
Oh, okay, so it turns out you can do padding and all with normal HTML tables, just need to apply it to the correct tags (in this case, th and td)
don't use tables for layout
tables are for tabular data
@meager anchor you can definitely nest flex containers
we do that on the wiki
oh well
im looking for a text color that looks good and is easy to read in this background
i have your IP address now >:D DDoS's 127.0.0.1
its local 😜
(that's the joke)
😂
that dark yellow GitHub looks ew
olive is bad in most cases
this is one of them
^^
not saying I could do much better but y'know, criticism.
get a better color
lol k
Have you tried a light washed out seafoam green, @marsh canyon?
or the same colour as squid dude's shadow?
that's what i was going to suggest ^
hmm
#D0E6F1
B0E0F0 is my guess
the light blue of the squid dude's shadow would be better imo
yeah same
oki
more consistent
the codes arent working
that's 9CDAF0
doesn't appear to be the same light blue of the shadow though
yea lil different
the hex code i sent (#9CDAF0) is the shadow blue
you'll have to google how to get them to work if you want to use it
🙏
🙏🏽
You could also just put a small outline around the text to make your preferred text colour pop out
how to add outline
firstName = models.CharField(max_length=25)
lastName = models.CharField(max_length=25)
def __str__(self):
return "{} {}".format(self.firstName, self.lastName)
class Period(models.Model):
classNumber = models.IntegerField()
class ScheduleItems(models.Model):
class Days(ChoiceEnum):
MONDAY = "Monday"
TUESDAY = "Tuesday"
WEDNESDAY = "Wednesday"
THURSDAY = "Thursday"
FRIDAY = "Friday"
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
day = models.CharField(max_length=10, choices=Days.choices())
period = models.ManyToManyField(Period)
def __str__(self):
return "Day: {} Class: {}".format(self.day, self.period)```
or do you guys know of other discord channels that helps specifically with django?
I think it's because ForeignKey expects a string as the first arg
not the class
try "Teacher"
@polar vessel
okay thanks, i'll give it a try right now
it's possible that it works with both though, I've just always used a string when I've done it.
from what i understand, a string is used if the Teacher model wasn't already created
mm, I see
yea still the same but thanks for the help
right, so that won't work by default I think
did you look at this?
might be relevant to this problem
that's what we're here for. hope you figure it out, I gotta run now.
Guys, quick question: if I have a form in HTML, and I want to store the responses locally, how do I do that?
is it a large data size?
like large enough to need a database?
or could you get away with localstorage in html
@marsh canyon out*
? @formal junco
It says “check them our today” instead of “check them out today” @marsh canyon
@ripe imp I think you would want to add a backend, like flask, to your form and make a database to store the data entered
@grand badge Thanks for responding.. yea, I'm actually done with it.. used Flask with sqlite to store database locally on the server the script is running on
Flask's actually brilliant for things like this
yes, flask is great ^^
For futurity, don't use WTForms unless it's a very standard form you're using, it's very restrictive
yep, i would use normal forms and request.form[] to solve your problem
Exactly.. and the best part is the arg for form is the name tag not the id tag
So, you can have properties of id tag as well
not a python question, but in CSS when should classes be used instead of IDs and vice versa?
good explanation, thanks ^^
😄
also, my memory is shit, #ids and .classes right?
yep
yay!
so just to clarify, i would use an id for my navigation/title bar, as there's only gonna be one on the page?
yes
alrighty cool ^^
note that you don't have to, I just use classes for everything
but that would be the case for an ID
yeah i'm aware, and for some reason it feels like it should be a class to me, but apparently not
ids are much more useful if you're building your website old school jquery style where you target everything manually with your JS
if you're using a framework like react where everything's components they're much less useful
flask is a backend, it's unrelated to how you set up your frontend
oh yeah haha sorry, i'm very tuned out when it comes to webdev
no worries, from a high level there are two main architectures
1 is templating where you create webpages as you need them in your backend and them send them to your user
the other is single page app where you send a blob of JS initially and then further exchange with your backend is data, and the frontend changes itself depending on that data
oh okay i see
the first one is what you'd see if you've ever used something like handlerbars or jade, or any kind of <h1> {{data here}}} </h1> thing
second one you'd see if you're using angular/react/vue/etc
ah alrighty
the key distinction to remember is your server, which is the computer that's running your app, and the client, which is the user's computer that you send html/css/js to
yep
flask runs on the server only
imagine just saying "oh yeah before you can use this site you need to install python and do python -m pip install flask okay cool"
yup
users don't like downloading things in general, which makes websites really nice
moved it up a little haha
you see, i'm using padding on a regular <p> for now as the title bar sorta thing
Search up "box model"
well you see my CSS is this ```css
#topbar {
display: block;
color: white;
text-align: center;
padding: 16px 16px;
background-color: #333333;
float: center;
margin: 0px;
}
#topbar:hover {
background-color: #111111;
}
if that's any use
ew css syntax highlighting is ugly
Try setting padding 0px too
you could have the box in your body (set body to "margin:0;padding:0"), with all the rest of the page stuff in a container that you apply the usual margin to
that's probably not the right way to do it though 
well it worked ^^
Could anybody put me on the right track when it comes to learning/getting familiar with Django?
Two Scoops of Django comes recommended by us, but it's not free
You can find it in our books section https://pythondiscord.com/info/resources#books
I have no problems with paying to learn, thanks a lot dude!
i learnt all my django stuff from the official docs
there's a really nice tutorial which familiarizes you with most basic stuff
I'll check that out as well, thanks!
My Flask url_for just results in a BuildError and I have no clue why, could anyone help please?
<link rel="stylesheet" href="{{ url_for('assets/css', filename='main.css') }}" />```
Never mind, figured it out
oh
hi
so like
i wanna put this specific part of a website in like a box
if u know what i mean
like a big card over a background
apparently it's called text overlay or smth?
think of it like iframing a site but not really if u know what i mean
anyone?
i found the perfect example at https://htmlcolorcodes.com/
kinda like how everything is on a card over a background
django or flask better
I need to FAQ that question, eh?
yes
Someone is good with Django ?
I installed TinyMCE in my project this morning and now I want to switch to CKEditor.
The thing is, when I execute my program (i uninstalled TinyMCE and all tinymce things in my code) the migration system block me.
And I cant do shit. If I delete the old migration, my program is dead.
When I execute I have this error:
ModuleNotFoundError: No module named 'tinymce'
And in the file app/migrations/0020_testmce.py
from django.db import migrations, models
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('site_web', '0019_auto_20180430_0025'),
]
operations = [
migrations.CreateModel(
name='testmce',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', tinymce.models.HTMLField(blank=True, null=True, verbose_name='Content')),
],
options={
'verbose_name': 'Test',
'verbose_name_plural': 'Tests',
},
),
]
So this file is blocking the execution of my program.
I edited the fucking migration file.
@fast saddle that just looks like some fancy styled scrolling divs
or block-styled list elements, looking at the source
Block styled?
I'm on my phone so I can't get adventurous, but try using your browser's HTML inspector to look at those will elements and their properties
@delicate otter well, since you used a field from tinymce, you need to re-install it if you want to run the migrations
I think you can reinstall it, create a new migration, and then squash the old migrations so the tinymce stuff is gone
I dont have the import tinymce line abymore and it seems gucci
did you just remove it?
Yeah
Well, if someone tries to run your migrations from scratch now and you didn‘t squash it, they probably can‘t
Unless they install the library, of course
erm, sort of new to web development. using a bootstrap starter template thing - just wondering how to get the items inside a navbar to follow the content's edges? if that makes sense
I want the navbar within here for example
oh I got it nvm
I just chucked it inside a container
what are the rules about asking HTML/CSS related stuff in here?
People asked before so I guess it is ok
body {
margin: 0;
padding: 0;
background: url("unknown.png");
background-attachment: fixed;
}
.topbar p {
position: -webkit-sticky;
position: sticky;
margin: 0 15%;
top: 0;
background-color: #555;
text-align: center;
color: white;
display: block;
padding: 15px;
transition: .5s;
}
.topbar p:hover {
background-color: #666;
}
```for some reason, the `position: sticky;` has no effect. i've tried quite a few different things with no success.
^ anyone got any ideas? ^^
it should be -webkit-position iirc if you're trying to add a webkit specific attribute
hmm okay i'll give that a go once i get back to my computer
is this a webpack app?
Anyone know of a way to give a django variable passed from a view a new value in a template?
could you elaborate a little on what you mean?
Hi Lucy. My django view passes a dictionary of values to my html template. I want to change the value of one of them in the html template.
Not sure of that can be done.
I saw an example of creating a new variable but not an existing one.
This value belongs to a form.
I think ajax might be the way.
Trying to avoid that if possible.
there's the with tag which can be used to assign a variable for the duration of a particular context, but that doesn't sound like what you're looking for
I think I saw that. Was not working when I tried.
your mention of AJAX makes me suspect you're trying to do something AJAX was explicitly designed for
your template can't be used to directly adjust server side state based on user input
I know ajax can do it but I rather do it in pure python.
the problem you are describing is the one JavaScript was designed to solve
you could make multiple HTTP requests instead, but I imagine that's undesirable as well
I just want to set that form value dynamically on page load.
Until user inputs data in the field.
you should consider the HTML that you send to a user final once it's been rendered, unless you've written JavaScript to adjust it upon arrival
are you asking how to change it after it's been delivered to the user?
or can you do so before?
It will be final on arrival but the data on first load will not be the same.
I feel like we're having a bit of a disconnect here. when a user requests a page, you have the opportunity to modify the page you provide to them in any way you see fit, and then the entirety of that page is sent to the user. at that point any pure Python solution becomes impossible, because browsers use JavaScript code to modify pages after they've been delivered
do you need to modify the contents of the page before or after it has been provided to the user? there is only one HTTP delivery
I see your point. It before the user gets the page. The page is requested and based on that page requested the form will ha e a default value that I want to set dynamically.
So the page is requested and my view renders the page. When it does this an if statement in the template checks if the form is empty or no value set. If empty it will set a value there.
and this isn't logic that can be performed in your view?
Hmm. I feel silly. I guess I like doing thing the hard way. Problem solved.
You rock lucy
glad to help! the XY problem crops up a lot, I find myself doing it all the time
good thing to be cognizant of if you find yourself trying to do something that seems more complex than it needs to be
Agreed! 😀
Can anyone suggest me some good tutorial on responsive web design?
@grand badge https://www.w3schools.com/html/html_responsive.asp
tanks Jason
can i have feedback? i want to keep it simple ^^
yeah, remove the background
hm okay ^^
:P
what should i set it to then? lol
alrighty then
is bootstrap "out" now
using flask and trying to create alert messages using bootstraps .alert and flash messages
the alert doesn't seem to be showing
"Mushy's blog"
right okay i'm back can i please have feedback? ^^ i'm lazy so here you go https://jsfiddle.net/boooL21x/
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
kingsley. huh. well it looks far better than earlier.
I'm afraid jsfiddle looks a bit fucked on mobile so I can't really review properly
yay thanks ^^
@tame viper an intel 8008 doesn't execute bytecode
shh
Change it or I'll destroy uuuuu
fine what to?
hm
any other opinions on that up there? ^ :D
looks pretty clean nice
i suck at web design tho so what do i know lol
actually that has nothing to do with me judging other webpages
i mean to be fair it's not hard when you're using a CSS framework
i would get rid of If you ever wish to get in touch with me for whatever reason, here are various ways in which you can do that.
contact me is pretty self explanatory and it will make it look nicer
also that shade orange isnt the best colour to put on white
looks good though!
okay noted thanks ^^
It's still bytecode 👀
anyone happen to have any good tutorials / examples of using google OAuth2 (requiring a specific domain if possible) to authenticate to a flask app? I'm trying to google around but most things I find seem to be finding many current / working examples
well if one could add reactions in this channel than yeah Id react
otherwise
the first one
there ya go. although truth be told this might be better for #ot0-fear-of-python in teh fyootr
ok! c:
well
its a website
so i think it qualifies 😄
i think if you want only python-related web-dev in here, there should be a channel topic specifying that
because right now it's really unclear
that is a good point
the opinion oriented voting bit is what made me think it seems a little more #ot0-fear-of-python-y, tbh. also there's lotsa peeps in there that like yelling about stuff they like
you're allowed to post it here. but you'd probably have more luck over in 
those guys love reacting to shit.
I wonder why reactions aren't allowed in here.
@polar robin 😄 i am just making a random flask app to learn
That's a library you're supposed to use it as part of a larger application
Hey guys maybe this is wrong channel to post. But is there a way to write a python script to get a list of the files that are loaded over the network?
What i mean by this is the following picture
Im trying to find a way to write a script to get a list of javascript files that are being called over the network, but i can't seem to find them in the source code.
"over the network" seems like a broad and maybe difficult to accommodate scope
maybe let's start with where you got that list of files. whatever's giving it to you seems to have a mechanism for seeing them
I'm trying to track something. But i think how the Web Browser will load pages is through following the links and adding them.
They should specify whatever scripts on the source page, unless there is script injection going on.
inspect get headers?
intercept them and then inspect?
nvm does get requests even provide that information
i'm trying to, after a user logs in on my website, redirect back to the last page
i'm using flask, and the flask-login extension, i'm not sure how I would go about it
save the route then render the previous template?
trying to get a good structure going for a flask app but it's not serving css in /static
(show create_app please)
from config import Config
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
map(lambda x: x.init_app(app), [db, login])
migrate.init_app(app, db)
from components.home import home
app.register_blueprint(home)
return app
from components import models
can you show how u linked the files in templates please?
linked? you mean how i linked to the css?
yes
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"/>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
is static in the same place as home?
no
im not sure this will solve your problem, but add type="text/css" in your link
didnt fix @grand badge
@hearty birch sure thing
from flask import render_template, redirect, url_for, flash, request
from components.home import home
@home.route('/')
def index():
return render_template('home/index.html')
sent pic for context if necessary
i think it’s cause it’s in a css folder
@hearty birch any thoughts on seeing the code
if ur templates are in the templates folder
how comes u render the template from home folder ?
Have you tried setting a static path in the blueprint?
@sage wedge use static_folder='../static'
hm that's weird
What's the working directory set in PyCharm?
Have you tried running the app file instead of using flask?
the folder i sent you is the working dir
@kind steppe yep, no difference
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"/>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
I don't know if it matters to Flask, but the path is built as if you were on Unix
tried css\main.css
Maybe that's why it works for me and not for you
Did you also change the static dir?
this worries me
it's not just unable to find the css or anything
it's just ignoring the static dir
no it isnt
did you change the static dir in Flask?
the same happens on our site https://pythondiscord.com/static/
Out of interest, what fixed it?
was it simple adding static_dir in the flask constructor?
yes
The Windows path thing is actually an interesting issue
I believe Django accepts / and changes it accordingly when on Windows, but I'm not sure
actually have a question re building out a flask app. Its not so much help as much as good practice questions. Should i pop it here or grab a help channel?
(the app is built and running fine, just curious with a rewrite)
you can ask here
cool, my app is mainly used for api testing for Slack. The questions aren't based around their api but more structure of the api side of the flask app. Currently I have an app folder that contains an __init__.py with the app routes (web facing, index etc) and an api folder with and __init__.py and routes there. I'd ideally like to split the routes inside the api folder into different files based on what they are doing (post message, post DM etc). but curious how to do it. Am I better just leaving it in this structure or is splitting it a good shout
Likewise should i bother spliting api and app in general like this
there’s actually a good talk explaining structure for flask apps
give me a sec, ill try to find it
cheers mushy. I can share the repo if that didn't make sense but a lot of stuff I found points to blueprints and I just wasn't sure if thats the best way still
https://youtu.be/tdIIJuPh3SI
It’s like 3 hours long, but if you have time read through the slides - it’s really good at explaining how to manage flask projects
Speaker: Miguel Grinberg Do you think that because Flask is a micro-framework, it must only be good for small, toy-like web applications? Well, not at all! I...
nice! I've been reading Miguels latest book (flask mega tutorial) and he does split the app a little but perhaps I mis-read sections, I'll check out the talk and go back through it
I guess his book would be a little more up to date on things then! he’s really good
i am reading his flask tutorial as you guys speak!
and at first glance your file structure seems pretty good - but i’m not 100% on your question, maybe someone else can chip in
ayy 
https://github.com/splinterific/Slack_test_app/blob/staging/api/routes.py so if you look here, I have /oauth /app_link etc all in one file. I'd love to have them all split into their own folders and files
@unkempt cypress so far how i am building my app is:
app
__init__.py
routes.py
templates/
static/
main.py
venv/```
just letting you know if it helps you
i call main.py for it to run
cool, cheers @dense sapphire . hmm I think I run mine a little different
oh I run slackbot.py but i'm pretty much identical
is your question concerning the routes file?
yeah i'm more curious if I should bother splitting it
Well, i followed the following: Init should initialize my app when it is run. It should call this and that and take care of what it needs. Routes concerns itself with routes. It is very clear where the routing happens
yeah, that’s how I have it
if routing were to be separate wouldn’t you have to import the app every time
me? Yes i import app into routes, and routes into init
so i guess there's nothing stopping me jsut importing app into "chat_routes" and importing it into the init everytime
and ignoring a file called routes
so, disclaimer aside, I work for Slack. This is a test app i use when people are having issues with implementating stuff through our API (method doesn't work as expected etc). I'll make it easier for me to test if I can quickly jump between files knowing its all located just in that file and not across others
you lost me 😜
its all good I'll pop back to the drawing board for now. you gave me some good ideas there @dense sapphire and @hearty birch , appreciate it
goodluck! Hit me up if you need antg later on. I am enjoying flask, so discussing it with people is a big plus 🙂
if you have a purpose for it, go for it I guess! you’re welcome, nice to meet a slack dev 😮
haha yea same here
still struggling with calling myself a dev 😄 I'm still seeing myself as support but I'll take the compliment
Guys i am working in a venv and i installed flask-wtf. It is giving me an error that the import was not done
from flask_wtf import FlaskForm
Error:
[pylint] E0401:Unable to import 'flask_wtf'
yes i tried running python in a terminal
I was capable of doing the import
(venv) PS C:\Users\Thunder\lulz\potato> python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask_wtf import FlaskForm
>>>```
Do you run python from within a virtual environment?
yes
in this case
because i only imported the flask_wtf to this project
outside of it it fails because i don't have it in my system
could it be a python path issue?
what are you running in
using vscode
maybe your text editor/IDE isn’t in the right venv
that’s what’s happened to me several times with VSC
naw i am in the correct place
check in the bottom right, does it say python (venv)
Python
no (venv)
but in my terminal i am in venv
and i am at that folder in vscode
cool, i'll look into it
Ctrl Shift P and Select interpreter
then choose the one in the current project path, should automatically detect the interpreter
aight, one secondo
Ah sorry, I completely missed htis
if python is your venv's interpreter, try python -m pylint
Since that python has flask_wtf installed, pylint should have access to it
i changed interpreters, as mushy proposed
error went pouf
but no (venv) is next to Python down there
alright
should restart VSC and it’ll be there I think
make sure you have the interpreter in your project path, not the global one
Ok so the workspace one (the project) is the venv one
and the global is the normal one, the main python one
yep
when you setup the venv, it makes like a few folders, the interpreter is within the Scripts folder
iirc
mhm it's in there
did it fix the linter screaming at you then :p
haha yep it did. I told you up there somewhere 😜
wait wait
did you mean Python (venv) as it should show as follow?
or just the Python of the venv should be chosen?
I thought you meant that I should see Python (venv) down there
🤦
I don’t think it always shows
but it should show there, it does for me anyway, but if it didn’t show but solved your problem then it worked i guess
Yea it doesn't. It was working when i said: i changed interpreters, as mushy proposed error went pouf but no (venv) is next to Python down there
mhm
I made sure which interpreter i was seeing and whatnot from the settings
I was stupid enough to think that venv directly switched interpreters
wait, check if your linters still active
okay great! glad you could solve it
Thank you mushy 🙂
you’re welcome! it’s because i had spent a long time trying to solve a similar issue
i feel yu!
hello
I was wondering if there is any way of creating a manytomany relationship between two objects
for both of them to reference eachother
?
yeah
django
but it says in the documentation not to use manytomany on both items
only on one
Why would you need it on one?
You get a related_name on the other object to "link back to"
can you explain that plz
does someone know of a Django CSS minifier? Something that automates the myfile.css -> myfile.min.css process would be really cool, but maybe I'm looking in the wrong direction with Django, and there's something else that does this.
can you not just use a normal css minifier?
Probably, yes, but having something that integrates with Django would be great
Have any suggestions?
https://djangopackages.org/grids/g/asset-managers/ @meager anchor
Asset managers for combining/compressing JavaScript/CSS and for versioning your media files.
loads of packages there that can do CSS compression and other stuff too
perfect, thank you
looks like this is the most popular
yeah
good luck 😃
thank you
hello i am getting an error that is talking about templates and i am not sure what it means
this is my html
{% extends 'partials/layout.html' %}
{% block content %}
<form action="{% url 'update_drink' %}" method="post">
{% csrf_token %}
<h5>Update Drink</h5>
<label for="name">Name:</label><br/>
<input type="text" name="name" id="name" value={{drink.name}}/>
<br>
<label for="ingredients">Ingredients:</label><br/>
<textarea name="ingredients" id="ingredients" id="name" value={{drink.ingredients}}></textarea><br/>
<label for="recommendations">Well paired with:</label><br/>
<select name="cars" size="4" name="recommendations" id="recommendations" id="name" multiple></select>
{% for snack in snacks.name.all %}
<option>{{snack}}</option>
{% endfor %}
<br><br>
<button class="btn waves-effect waves-light" type="submit" name="action"> Submit
</button>
</form>
<br>
<a href="/vendcart" class="btn">Go Back</a>
{% endblock %}
the views.py
def update_drink(request,id):
drink = Drink.objects.get(id=id)
snacks = Snack.objects.all()
context = {
'drink': drink,
'snacks': snacks
}
if (request.method == 'POST'):
drink.name = request.POST['name']
drink.ingredients = request.POST['ingredients']
drink.recommendations = request.POST['recommendations']
drink.save()
else:
return render(request, context, 'update_drink.html')
the html calling the update function
{% extends 'partials/layout.html' %}
{% block content %}
<br>
<h2 class="center-align green lighten-3">{{snack.name}}</h2>
<div class="card">
<div class="card-content">
<h5>Ingredients</h5>
{{snack.ingredients}}
</div>
<div class="card-content">
<h5>Well paired with</h5>
{% for drink in snack.recommendations.all %}
<a href = "/vendcart/details_drink/{{drink.id}}"> <u>{{drink}}</u></a>
{% endfor %}
</div>
</div>
<a href="/vendcart" class="btn"> Go Back </a>
<a href="/vendcart/update_drink/{{drink.id}}" class="btn"> Update </a>
{% endblock %}
i get this error
TemplateDoesNotExist at /vendcart/update_drink/6
{'drink': <Drink: Soda>, 'snacks': <QuerySet [<Snack: Potato Chips>, <Snack: Granola Bar>, <Snack: Ham and egg sandwhich>]>}
I don't know if I'm getting you right, but the last href in the last code block, points to the link in the error and I don't know where you store your drinks ids but it seems like drink with id 6 doesn't exist.
mmmmm
well they are in mysql
in a table
but look when i access soda which is the drink i want to update it's id is 6
shows this
<@&267630620367257601>
Well the exception is a TemplateDoesNotExist
So that should probably give you some hints
yeah just i am not sure why it is doing this
{'drink': <Drink: Soda>, 'snacks': <QuerySet [<Snack: Potato Chips>, <Snack: Granola Bar>, <Snack: Ham and egg sandwhich>]>}
Because the template does not exist, I imagine
since they r both in different tables
mmmmm idk what it means by template then
yeah okay now i know what u r refering to as a template
That's what they're called lol
sorry new at this
update_drink.html, in your case.
It's okay
just started learning about 2 days ago
about django at least
but my template is saying how it wants it to be displayed
so why does it say there is no template to display the info i am requesting
It's probably not looking for the template you think it is
Well how did you define what template to load?
I actually have no idea, since I don't use django
the point I'm making
is that you defined a template for the other page
so you should define a template for this page as well in the same manner
and then, yknow, make the template
I'm doing a Django project using channel layers and websockets to run boardgames, simplified multiplayer.
Now I want a timer of sorts such that after 30 seconds after a client makes a move, the server replies, perhaps ending the game if the turn timer went out.
So I'm using threading.Timer, calling a class function in the Consumer after some time, and that seems to work. Might be a bit wonky if the client disconnects.
Is this alright, or is there some fancy Django timer, some async waiting/timer solution? Is the threaded Timer async safe?
there is a fancy async timer solution, yes.
but I don't know if it's gonna solve anything to switch to that approach.
I'm not sure why you'd use async code with django
Because AsyncJsonWebsocketConsumer
yeah
Wtf is that name
makes sense
Long
Base: AsyncJsonWebsocketConsumer, AsyncConsumer, BaseConsumer
Uses: channel_layer (RedisChannelLayer)
Handles websocket connections from the users
Well, it's what I'm using. Could you show me the async timer solution?
def hello():
print("Hello world!")
print("Starting timer")
t = Timer(10.0, hello)
t.start()
Current implementation. Unsure if this is safe in an async environment.
essentially you call the relevant asyncio functions with a timeout kwarg and then catch asyncio.TimeoutError
https://docs.python.org/3/library/asyncio-task.html some info here.
but I mean, the stuff you're doing has to support that approach
I'm not following.
Timeout sounds like I have a time limit. I want it to execute in x time in the future.
oh. sorry, I misunderstood you then.
My goal is that when it's a player's turn, in chess for instance, it'll start a x second timer to check if they've made a move yet. Else, forfeit.
Perhaps I could just use async sleep?
I mean.. yeah. isn't that what sleep is for?
sure you could schedule a task x seconds in the future but that sounds like a lot more processing to achieve the same thing
I'm not exactly an async expert though, I never get to use it at work.
so I might be completely wrong
It could be relevant as I actually need to start a timer for another client's Consumer. If player A makes a move, it's B's turn.
Although I'm not sure if I can communicate between them.
But I already announce new moves to all clients, so the player B will be aware that it's their turn and how much time they have. Just a matter of knowing where to handle it on the server. x_x
I mean, tbh, it sounds like django and backend websockets is a pretty dubious tool for this job :D
but it does sound like a fun experiment.
I have no idea how else the server would communicate with the client.
Unless sure, the client does everything and the server is REST or something.
yeah but do you have the websockets running in the django app itself?
Essentially, if player A makes a move, I want to update ALL players in the game about the new move. That has to be done with web sockets, no?
yes, web sockets need to be part of it, that's true.
but normally they would just communicate directly with.. well, essentially just with a database. or a seperate server that's just sitting there handling websockets in a single session
although I will say I've got websockets in some of my flask APIs too
but I've always felt a bit like it might be a bad idea :D
Yeah, I'm using Redis, which is I guess a more lightweight database that automatically clears after the game is over, etc.
Using this as a base for the channels part.
Multi chat client, like an IRC.
For the record, using await asyncio.sleep(n) freezes the Consumer, which I guess makes sense.
Anyone around with experience of Django? When loading template snippets into a parent template by passing a render_to_string(snippet_path.html) context value, is this less performant than pre-loading the template snippet before request-time and simply passing the pre-existing form snippet to the parent template when returning them?
Or would it not matter at all?
@silent plaza are you sure you don't want to use template inheritance or {% include 'snippet_path %} instead of doing this yourself?
What is your favorite django hosting company?
@Raijinn @meager anchor I use include as well for things like this.
My PC xD
Yeah I used that and pythonanywhere. I have not tried Heroku or any others out there. I was curious on what others found success with.
GDPR. https://techblog.bozho.net/gdpr-practical-guide-developers/ states
Allow users to edit their profile – this seems an obvious rule, but it isn’t always followed. Users must be able to fix all data about them, including data that you have collected from other sources (e.g. using a “login with facebook” you may have fetched their name and address).
alright so, if I have users log in to my app with Discord's OAuth, does that mean I need to allow users to edit their username obtained from Discord, or is it okay if I say "To update your username, update it on Discord and press this button to refresh our OAuth information about you"?
uuuugh the evil EU law
hey is there someone that has ever config nginx with cloud9 and apache to server php files?
good morning, im wanting to do a website for my discord bot, are there any resources that i should be looking it
i really like the simple layout of https://baronbot.github.io/
I only heard bold things about https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
not python though
Good things *
i dont really need to use it i believe
If you only want a page you can use something like Microsoft expression web
Someone here probably knows better though good luck again
you could use UIKit to achieve something fairly similar, structurally. you'd need a little extra css and js, and those stats need to come from somewhere, so it does need a backend with access to them in some way or other.
so I'd be reaching for Flask to ensure I had access to that data.
but beyond that, I do think it's a good habit to start using stuff like flask as your backend anyway, cause it's super useful to learn.
i dont really need any bot access though, just display the help file
I mean like.. the number of servers and so on
that data has to be fetched from somewhere.
and it's neat.
true dat, but that can just be pulled from discorfbotlist api
how would i access the data if its on a different server though...
so if I was gonna make a page like that for a bot I wrote, and I agree that the one you linked is quite nice, I'd probably use a stack of flask, gunicorn, UIKit, and a little extra js and css sprinkled in.
that gives me the powerful python backend where I can solve problems like "fetch data from an API" super easily, it gives you gunicorn so you don't have to fuck with apache, your wsgi app just runs, magically. it gives you UIKit so that you can structure the website and have things look fairly decent right out of the box, and then you can polish it with js and css to make it shine once you've got the basics down.
also teaches you a bunch of really excellent tech that is used all the way up to industry level
for the record, the pythondiscord website runs on uikit and gunicorn-served flask.
ahhh sweet
okies, so is there somewhere i can start reading all this stuff
also total noob learning from scratch 😄
start with the basic flask app
get a hello world up and running
then when it works locally, get it gunicorn hosted on your server. that should all be fairly straight forward.
is gunicorn a replacement for nginx?
yeah. I mean, that part is highly optional
you can use nginx if you want
but gunicorn makes it ridiculously trivial to do python webserver stuff
if you recommend gunicorn then i shall go with that
i like that
the way we do it , we point nginx at gunicorn so nginx is still the big boss for all incoming connections on the server.
but.. that's because we have so many different types of webservices running on the server
and gunicorn is specifically a thing you use for python webapps like flask
the flask website has a decent basic tutorial
you're not gonna need very advanced flask features for a project of this scope.
nope not really 😃
its not something i would have looked at, but the bots doing pretty well at the moment
and its all a learning experience so all is good
yeah
yeah you should totally do it though. a python backend is just so nice to have. and it's really quite easy to set up that way.
if ever in the future you're like "fuck, I really want this data on the website but how do I get it?", then if you don't have a backend to lean on, you have to solve it in javascript or something.
Urghhh
and that's a bad idea. javascript is great for the little things. don't be solving big problems in it.
so when that day comes, you'll be happy you have python
it makes it absolutely trivial to put advanced features out.
not to mention, essential if you wanna introduce a database to the mix..
maybe you want users to be able to log in and change a config file for the bot in the future
you know, shit like that?
hmmm i dont really need a database added right now... although, maybe server setting.s... yeah yeah
yeah so if you end up going down that path, this infrastructure will save your life.
haha
I'm just saying, this is like.. hours of extra dev time, but you're setting yourself up to be able to do whatever you need to do in the future. building a solid foundation.
it's worth doing.
haha, not bad
well, get your flask hello world running on that
and then poke me and we'll take it from there.
you'll only need that in production
nginx -> gunicorn -> your app.
the gunicorn website has great, simple instructions for how to use it with nginx
but you should get the flask thing working locally before you do that - flask has a built in webserver so you can just run the file and it makes itself available over your local network.
where do I actually need to put my flask template folder? i have my flask app in a package, and judging from the docs (http://flask.pocoo.org/docs/1.0/quickstart/#rendering-templates), I need to put my template folder in there. so i have:
└── web
├── __init__.py
├── app.py
├── static
│ └── base.css
└── templates
├── base.html
└── index.html
and I run it using
$ FLASK_APP=web.app flask run
but that tells me TemplateNotFound. I also tried it with putting the templates folder in the top level directory. Where do I need to put it then?
show me your render_template
from flask import Flask, render_template
app = Flask('something')
@app.route('/')
def index():
return render_template('index.html')
oh no..
the name needs to be web, right?
well then, that works
sorry for wasting your time :P
I'm happy to rubber duck whenever
pssst
@deep cave
thats a flask app served by apache and using gunicorn
nice
i LOVE digitalocean
yeah its amazing :D
their helpfiles are the best in the world
i only wanted a 1 page website but ohhhhhhh no
mutters
took you all of ten minutes
okay now learn some basic UIKit and make it prettier.
why UIKit over Bootstrap or other frameworks
there's no compelling reason. pick the one you like.
bulma, bootstrap, uikit, whatever you like the look of.
I like uikit.
bulma is nice
bootstrap feels a bit older
If I were to make a site that had a collection of small web apps I make. Should each app be a separate flask + gunicorn setup. With nginx serving them ?
Or is it ok to do them all in one flask setup
I'd probably just have a single flask app serve all of them. ¯_(ツ)_/¯
its' really a question of personal preference, though.
and it totally depends on how big these things are.
Yeah I'd rather keep it together. Just wanted to double check that there wasn't a reason not to
If there will only be a handful of static pages is there a point to use nginx?
Or is it ok to serve static pages using flask
you mean with the built in flask webserver?
right. well, gunicorns own guides do recommend you set it up behind an http server like nginx
I'm not really sure how well it works without nginx, I've never tested. good question.
but I'd just spring for a proper solution anyway. no compelling reason to half-ass it, is there?
I've never tested.
The users will test it :D
My plan is to make my site entirely in a 5 dollar digital ocean droplet
yep
So trying to be efficient
I guess you could try ¯_(ツ)_/¯
Yeah I am going to thanks
apparently gunicorn is insecure without a server like nginx - something about ddos attacks.
Well then I'd say that's reason enough
check the top answer here
by one of the gunicorn devs
very informative
Is the current way of doing things nginx , flask+gunicorn in separate containers ?
Thank you
containers as in docker or something?
Yes
I got gunicorn and flask both in a single docker container on my projects, and then I run nginx outside of the container.
Ok that's what I was thinking
that's a fairly tried and tested way of doing it, yep.
But nginx isn't in a container ?
no, not on my setup.
And then I suppose if I needed a database that would be outside of a container as well ?
in the setup we have on pythondiscord, the database is actually in a separate container.
Ah ok
often "what do I put in a container" boils down to what problem you're trying to solve. it can be a bit subtle.
Yeah I've never used them before. Only vms
are you a devops team and the containers are built by the developers? well, then you need to expose anything they might want to change.
are you gonna deploy to many servers? you'll need the containers to make it easy to propagate
or migrate
etc
but for your use
it's not super important
I'm just making stuff for me to learn
So using containers is a good learning experience
so I mean, you could put everything in one container, probably, and just leave nginx on the server itself, and you'd probably be fine. but having a separate container for the database will probably teach you more useful lessons
because then you need to play with inter-container communication and stuff.
and uh, on this topic, #414737889352744971 is probably a better place to go for information
our devops master, Lord Inver, could talk about this for days
Yeah I like that idea
personally I'm kind of a docker noob
Ok cool
(his lordship personally taught me everything I know :P)
I'd say in short there'd be 2 things to keep in mind to decide whether things should be in 1 docker or seperate.
- Can A run withotu B? If no > together else seperate
- Might B have to scale up without A > has to be seperate.
If you have 1 and 2 combined you can use like docker-compose to combine docker containers into a single application.
playing around with UI kit and actually really like it
UIKit is lovely
no u ^^
Aw
wut
is your question "can you have flask views split over multiple files like discord bot cogs"?
yes
that's right
i have a api and a website website part of the website and i want to keep it organized so two files and 1 that runs both
a quick search brought me this for general patterns for bigger projects:
http://flask.pocoo.org/docs/1.0/patterns/packages/
and this for blueprints, which also outlines what they are used for, and this sounds like what you want
http://flask.pocoo.org/docs/1.0/blueprints/
thank you sir
Hey guys, does anyone know, in Django, how to temporarily disable auto_now and auto_now_add fields attribute for bulk_create? I would need it to save me a lot of time 🤔
?
Adding a parameter to init comes to mind but I'm not quite sure if it would work or not since I'm pretty ignorant about databases
class This(models.Model):
def __init__(self, *args, temp=True, **kwargs):
super().__init__(self, *args, **kwargs)
self.temp = temp
some_time = models.DateTimeField(auto_now=self.temp, auto_now_add=self.temp)
This.objects.bulk_create(
This(foo=bar, temp=False)
This(bla=blabla, temp=False)
)```
