#web-development
2 messages Β· Page 47 of 1
But it still doesnt work for me
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# DB STUFF
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://myurlhere'
app.secret_key = '3904-39034-094-3290-'
db = SQLAlchemy(app)
from controllers.database import Idea
from helpers.user_post import Post
Idea.initiate()
yea
I'd try to change the way you're organizing the app
For consistency, I always organize it as Miguel Grinberg suggests
But I really can't catch why is this occuring to you
I'm also not sure if you have to name your models file as models.py
I dont think I need
Maybe that's a constriction in Flask
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',
upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
# Resize Image
basewidth = 300
img = Image.open(self.image.path)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save(self.image.path)
This was the example from my practicve project that used it. I'm giving up Django to learn Flask I think though so Im probably nto going any further with it.
I would use Django if I was making a full featured blog that I needed to just be a blog that has everything a blog has. Otherwise Im tired of dealing with modifyuing it. Id rather just start from the bottom.
@rustic pebble Do you use flask-bootstrap or do you just do it manually? I think im gonna skip this for now.
I do it manually
Every time
I usually take a template and change the shit out of it
I am just bored to build the foundation
I just saw this extension and foudn that it overly complicates using bootstrap which is already just simple af
So if theres no reason to use this extention I wont
What are Blueprints?
Im probably getting ahead
Can someone tell me why this isnt working as it should?
for (item in postsbody) {
if (!(postsbody[item].innerText in posts_in_dom)) {
if (postsbody[item].innerText) {
posts_in_dom.push(postsbody[item].innerText)
}
}
}
The save method is essential if you want to make any changes to the image before you save it.
Which you typically do because otherwise people will upload 4k images lol
a small website I made so people can share ideas
and I can benefit off that
took me around 2 hours
Mobile friendly as well π¦
Anybody here know any good tools/libraries etc... to help me make user post feed which also connects between my react front end and flask backend?
@manic siren you trying to connect flask to your data source?
I suggest sqlalchemy to interact with your db
@fresh dock Well right now Im just trying to figure out the React part and how exactly to do this. I've been using React for about 2 weeks and things are very confusing. I tried asking in the React discord but nobody really helped me so I thought I'd try here
@manic siren never used react myself but I'm literally building an indie social network platform startup on flask and sqlalchemy so I can probably answer all your other questions
Oh god react looks like a strictly worse jinja2
Kill it
Kill it with fire
@manic siren are you constrained to using react or can you switch to an actual templating engine like jinja2 which comes pre packaged with flask
@fresh dock Im only allowed to use React since thats what we've been learnining in my bootcamp and just in case I have issues my instructors will be able to help me
Ah
@fresh dock I'll definitely have some backend questions for Feed stuff so I'll def come to you
I appreciate it!
Right now I'm trying to build a morning commuter app. The feed idea is basically similar to what we have on discord. To the left, you have your different channels which in this case would be my trains. Then the Feed which hosts the comments made by users and a comment box below the feed where the user can post a comment.
@manic siren so I'm a back end guy. Do you have your flask app connected to your data source yet or no?
Not yet, I was gonna format my front end first then go to the backend since the front end stuff is what I have most trouble with
At least doing this project gives me a sense of what area of development I'd like to be in lol
Ah
Yeah
Front end is a bunch of witchcraft to me
Back end is a bunch of black magic to my front end business partner so...
We work well together
@manic siren if you want a real world example of sqlalchemy to work off of: https://github.com/ruqqus/ruqqus/blob/master/ruqqus/classes/user.py
It lets you turn db columns into object properties and automagically handles all the sql in between
Ahhh interesting
Up until now I've been manually doing it sqlite3
Thanks! definitely gonna take a look into it
@manic siren yikes. If your thing is gonna take any kind of user generated input, then you definitely want something like sqlalchemy to handle all the sql
Otherwise every function is 1) an opportunity to fuck up, and 2) an opportunity to not properly sanitize
By sanitize what do you mean exactly?
@manic siren I refer you to xkcd
@manic siren basically, if you fuck up escaping while inserting your user-generated input into an sql query, you end up with the db executing that text as sql code
Ahhh I see
If you use a package like sqlalchemy, it takes care of all that for you and you never have to worry about it
Well by manual I mean, I have a function that inputs the user for me
Ill show you an example
In the comic, the school server fails to escape the ' in Bobby Tables's name
Which makes the db think "end of name input string"
Followed by a ); to close out the query and then it proceeds to execute DROP TABLE Students
There are several other tricks that can be exploited in other ways
lolllll thats hysterical
def save(self): #saves file
if self.pk is None:
self._insert()
else:
self._update()
def _insert(self):
with sqlite3.connect(self.dbpath) as conn:
cur = conn.cursor()
sql = """
INSERT INTO {} (username, encrypted_password, f_name, l_name, email)
VALUES(?,?,?,?,?);
""".format(self.tablename)
values = (self.username, self.encrypted_password, self.f_name, self.l_name, self.email)
cur.execute(sql, values)
def _update(self):
with sqlite3.connect(self.dbpath) as conn:
cur = conn.cursor()
sql = """UPDATE {} SET
username = ?, f_name = ?, l_name = ?, crypted_password = ?, email = ?
WHERE pk = ?;
""".format(self.tablename)
values = (self.username, self.encrypted_password, self.f_name, self.l_name, self.email, self.pk)
cur.execute(sql, values)
I was told the ? prevent sql injections
Not that particular implementation unfortunately
Also you don't want to be making and killing connections all the time
That's sloooo
@manic siren ^
Also are you encrypting passwords? Or hashing them?
Werkzeug (which comes packaged with flask) has a proper function for pw hashing and verifying
Salts and hashes and all that in one function call
Does anyone know whether I can link a function when creating a new element?
Basically I am creating a button and I want to add an onclick function to that new button
but I am getting objectpromise whenever I try to set it
downvote.setAttribute('onclick', update_votes('downvotes'));
oh nvm found it
@fresh dock Im using bcrypt to encrypt my passwords. Makes for checking them so much easier lol
I'm a little worried about the SQL part of flask. But I'll have a look at sqlalchemy when I get to it.
Im so far liking it more than Django.
@native tide You will find it very easy
You just define classes
And then just update objects
Nothing more
Nothing less
I want to edit bootstrap colors. I think I need to learn how to compile scss down to css to do that effeciently.
I could just change the colors around at the top under :root {} but...
these colors and variations of them are referenced too many times not using var(--color)
That I basically need to learn scss to do this.
I could do a global find and replace... but...
There is going to be a mess when I get the colors slightly off, which they will be at first.
Dude Im looking at how sass can adjust your colors for you
and im sold
I have to learn this
yeah... I enjoy CSS. The part of front end that I dont like is JS. But thats only because im not very good at it yet.
So Im not going to deviate to learn it now
But eventually need to
sass that is
I just found a program to generates the variations in colors for you for now haha

Well, overall, sass appears to just make css easier for you if you ever have a very specific color scheme in mind or something like that.
Its just one of the other million things i need to learn that i can only do one at a time
I only learn things I need
So idk
I usually just buy/use and fully customize templates
aaargh
setting up servers is so hard
My first websites were before the age of bootstrap, and back then I put a lot more effort into just laying out a page. This is back when I was a kid. (getting back into this kind of thing is kind of my midlife crisis if you didnt know that)
These days I dont typically use an entire template. But I do look at the documentation for how to show this kind of thing, and then I piece together small templates into something bigger... made up of templates.
Its a lot less work. Frankly, I think it makes the entire Internet look exactly the same but...
I also know that its a level of polish that the average user expects today.
It is what it is
We see bootrstrap and we immediately realize, "ah, that's the bootstrappiest thing ive ever seen"
An end user sees anything that inst bootstrap and they think, "What is this the 1990s?"
shrug. lol. Its less work for me
Well that is why I heavily mod everything
And xD i am 18 I still have a lot to learn
And I donβt really think that people mind if you use bootstrap as long as you are creative about it
I was this kind of thing from age 13-18. At age 18, when I was free of my house, I spent significantly less time on my computer and went in a different direction at school.
Funny that Im back into what I was into when I was a kid now
Eh idk
I love coding
But I also have a very active social life
It is very strange since devs have been given a bad reputation concerning socialization
I want to study CS
But unis here are hard asf to get into
Those who get are only those who can remember whole books and not actually people who are worth it
I got to school and I teach my professor about programming haha
See, I wasnt a programmer as a kid. I put together pages in HTML and CSS. I didnt know JavaScript at all. It wasnt like a thing I was a good at. It was a thing I did because at that time, all your little friends at school would have stupid little geocities pages.
But a year or two ago
I felt something was missing in my life and I needed a hobby
And I happened to get a lot more into it than I was as a kid
Well jt might be the understanding you have
Before I started using js/python/c#/etc
I was afraid of anything that had to do with backend
But then I just took a brave decision to learn python
And it naturally hit me I need more knowledge on others as well
I just didnt have access to the concept of backend. I remember knowing that if I ran my own server or could afford hosting that I could use PHP to do things you couldnt do without PHP.
At the time that was the in web lang
But I didnt have access to that stuff
I do now
lol it happens
And I have like 4 projects on delay
Back then they did not have simple web servers that opened up in your IDE
But eh, idgaf I will get a job in summer
It took... it took more to be exposed to these things back then
Now almost anyone can learn.
True
But also not true
People in school think I should be working in Nasa rn but the truth is that 80% of people here are better than me
Its all about perspective
Hm, I suppose. What I'm saying is that... the best programmers are the ones whose family are educated and have a lot of computers around and get them started very early. Today almost any kid can be like, "I want to be a programmer" and download some IDE and is on his way.
At one time you needed books.
You needed servers.
Real onmes
And the list goes on.
Its easier to get into today.
Hmm well actually I was exposed to computers very early
And I was also prompted to be the creator not the user
So I sort of grew up with the mind scheme of developing
yeah. Well it was definitely always a potential thing in me that I didnt pursue heavily until later.
Well coding was considered a hard thing 20 years ago
And btw I dont agree with your Ide approach, IDEs can help disorientate new programmers because of their infinite features
How are you going to explain Git to someone who can barely print hello world
What about file structuring, pep8
Etc
I pretty much agree. I know a kid who is like 15 taking college courses and he just failed his first test because he relies on the IDE
you're preaching to the choir lol
I think that it becomes a useful productivity tool but while learning Im grateful I became a drilled typist.
Hey I have a question for you if you know the answer, othewise Ill search
I dont want my login form to have field labels. I want it say grayed out, inside the form while its blank: "Email" and "Password" and when you select it and start typing it replaces it with darker normal text.
Flask.
Im fully on Flask now.
Its much better for me.
That is placeholdwe
Placeholder
And replacing with dark is css
But if you want to add a background text
You just do <input placeholder=βtextβ></input>
Replace text with the value you want and you got it
Right.
Flask is perfect
Got it, thats much easier than i thought haha
Let me see
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
flash(f"Account created for {form.email.data}", 'purple')
return redirect(url_for('home'))
return render_template("register.html",
title="Register",
form=form)
and that goes to this
<legend class="border-bottom mb-4">Join Today</legend>
<div class="form-group">
{{ form.email.label(class="form-control-label") }}
{{ form.email(class="form-control form-control-lg") }}
</div>
<div class="form-group">
{{ form.password.label(class="form-control-label") }}
{{ form.password(class="form-control form-control-lg") }}
</div>
Where can I put that placeholder prop?
class RegisterForm(FlaskForm):
email = StringField("E-mail",
validators=[DataRequired(),
Length(min=4, max=32),
Email()])
password = PasswordField("Password",
validators=[DataRequired(),
Length(min=8)])
password_confirm = PasswordField("Confirm Password",
validators=[DataRequired(),
EqualTo('password')])
submit = SubmitField('Sign Up')
forgot that part
am I? lol
Sorry, do what you got to do
Well I havent slept so im ok
I really shouldnt
same
I suppose you have a db model?
Not yet, that's next. I dont even have a database yet.
I do but its not in the flask app
I was just curious about this appearance thing
boom
so you dont use wtforms?
<legend class="border-bottom mb-4">Join Today</legend>
<form action='/register' method='post'>
<div class="form-group">
<label class='form-control-label'></label>
<input placeholder='E-Mail' name='email'>
</div>
<div class="form-group">
<label class="form-control-label"></label>
<input placeholder='Password' name='password'>
</div>
</form>
This should be html
this should be python
Right, if I was writing it all as HTML, I could do that.
Do you write custom validation?
and csrf?
@app.route('/python', methods=['POST'])
def register():
data = request.form
email = data['email']
password = data['password']
hrm
Word.
haha, yeah I know that. Thats another thing Im concerned about is that Django takes all of this for you. Im happy to learn to do it manually but. yeah
Im aware of that
Usually what you would want is a hash
For sure.
Havent got that far, another thing Django does for you.
I'll get there. Im a pretty thorough studier though.
Well tbh
You should just try to do things the simple way
Utilizing jinja is ok
But as you see it is not optimal
No thanks.
I never utilize jinja
This is what I literally do to keep myself from touching jinja
No thanks. But thank you.
Sure
But you arent going to get live updates
with that
That is true, but js allows you to do
50 times more things
with the data you get
Like I usually create diagrams, analytics, etc on my websites for the admins
How are you going to do that with jinja
And also server side rendering doesnt allow responsiveness to occur
Whereas you can just refresh elements with js
Im not trying to say I'll never learn to use JavaScript. Its just not what Im focused on right now. I started playing with React a little bit but then I found myself more intersted in learning Flask. I intend to make full use of Flask. I like Python more than JavaScript. Infinitely more.
I know that I will have to use it sometimes.
But I dont need to rely on it.
You call it the easy way and maybe thats how you feel but templates are not difficult.
Using JavaScript when yopu dont need it is like taking a flamethrower to a cock roach.
But I get that there are times its the only thing that can do the thing
You are right
But then again I donβt agree entirely haha
Lets just agree to disagree
that's cool, nothing wrong with that.
We agree about Flask at least. I like it as much as you do haha.
I think its possible I will be missing some features that Django has but one thing I like about that is...
- learning to do them myself
- not having to deal with the bloat when Im done
When you learn to do Django, theres a huge part of it that feels like, "Well damn, I couldnt have done any of that by myself."
Its literally all done for you. If you're cool with default, its already done. lol
The problem is, I find it easier to just build from the bottom that try to adjust default behavior constantly
Its possible, but its annoying.
So yeah
the main reason I use Django is the ORM
How can I emit an event in a flask route using flask_socketio? I can't seem to get a response to my client
@manic siren you should be bashing passwords and comparing the hashes. Werkzeug.security has a great function for this
The ORM is nice. I might look at other ORMs after seeing it in action.
I'm thinking of using peewee for a project i have in mind
The creator of it very active on reddit
@vestal hound agreed. Django's ORM is awesome. I even have a stripped down version of django where only the ORM (and migrations) works because I find it far superior to SQLAlchemy
That's interesting. You use Django just to migrate to your database?
Django's ORM is probably the best thing about it.
I have this looking all decent. Now to actually connect it to a database. I might do this part tomorrow. This is Flask.
I have yet to see what its like doing the database part with Flask yet.
I just started the SQL Alchemy lessons. It seems like its pretty similar... At least so far
Hello all,
I have just completed my first project ever. I have made a simple Stock Management API. Since i have never deployed a project to the production environment before by my own, i don't know how to do. Can you guys tell me how to do it? I want to deploy it to Heroku. Project link:
@native tide sorry for not replying I actually just died on my pc haha
@native tide as I said SQL part of Flask is almost identical to classes
Let me give you an example
After conntecting to your db you need to somehow create a table
class Idea(db.Model):
__tablename__ = "ideas"
id = db.Column(db.Integer, primary_key=True)
title= db.Column(db.String(50))
post_body = db.Column(db.String(50))
author = db.Column(db.String(50))
upvotes = db.Column(db.Integer)
downvotes = db.Column(db.Integer)
def __init__(self, title: str, post_body: str, author: str, upvotes: int, downvotes: int):
self.title = title
self.post_body = post_body
self.author = author
self.upvotes = upvotes
self.downvotes = downvotes
This creates a table and adds the items you see as db.Column as columns
Then if you want to update a row, you just need to query the table by doing:
ideas = Idea.query.all()
This will give you a list of objects that are essentially the rows of the table
And you can access them directly as if they were just normal objects
If you want to update a row you can just do:
ideas = Idea.query.all()
for idea in ideas:
if idea.title == 'MyTitle':
new_idea = Idea(idea.title, post_body='updated post body', author=idea.author, upvotes=idea.upvotes, downvotes=idea.downvotes)
db.session.add(new_idea)
db.session.commit()
And that is essentially the core elements of SQL with flask
Best possible way to override the indexview of Flask Admin without running into collision whole time ?
Here is my conf file, in /etc/apache2/sites-enabled:
<VirtualHost *:80>
ServerName artybot.xyz
DocumentRoot /home/artemisweb/artemisweb
WSGIScriptAlias / /home/artemisweb/artemisweb/artemisbots/wsgi.py
WSGIDaemonProcess artybot.xyz processes=2 threads=15 display-name=%{GROUP} python-home=/home/artemisweb/artemisweb/venv/lib/python3.8
WSGIProcessGroup artybot.xyz
<directory /home/artemisweb/artemisweb>
AllowOverride all
Require all granted
Options FollowSymlinks
</directory>
Alias /static/ /home/artemisweb/artemisweb/main/static/
<Directory /home/artemisweb/artemisweb/main/static>
Require all granted
</Directory>
</VirtualHost>
However, when I attempt to access the website, it just times out. What am I doing wrong? I have recently purged and reinstalled apache2
i'm struggling with django-storages S3 backend, running django1.11 and python3.6 (long road towards getting the whole system up to date...)
we have some components that generate files and save them to FileFields; currently using storages.S3Boto3Backend i can't successfully save these FileFields. if i manually create an S3Boto3BackendFile and do model.file_field = s3file_object it says the file is there, but calling either model.file_field.save(filename, s3file_object) or model.save() resets me to FileField: None
the file does appear to get uploaded to s3 successfully, but the model doesn't know where to find it!
@elfin solstice - anything in the logs for apache? is this a plain wsgi app?
ok. fiddled around and found something that worked but it doesn't seem to match the intended behavior, and based on my limited understanding of the code i don't understand why this is the only way that works, but for my case, if you create the file separately, then do model.file_field.name = filename and model.save() ... it works properly.
@magic blade
Couldn't find any logs. It's django
Any reason why I can't make any post or get requests to my flask routes when I have an open socket? (using flask and flask_socketio together)
So, import hell is apparently a common problem in Flask? Or have they found a modern solution and agreed upon best practice? It seems there are a variety of approaches to it.
@native tide what do you mean?
I havent had the problem yet myself but Ive heard at least two people talk about it.
https://tracy.dev/how-to-mitigate-import-hell-in-flask/
https://www.youtube.com/watch?v=44PvX0Yv368
While that video says its about package structure, what its about is refactoring package structure due to import errors.
A starter for your Flask app. Kind of like sourdough starter, but less tasty.
In this Python Flask Tutorial, we will be learning how to restructure our application into a package rather than running from a single module. This has major benefits in terms of importing modules across our application. Let's get started...
The code for this series can be fo...
What Im asking is, these problems seem like the might be something that has been fixed.
And Im wondering if there is best practice now
mm yeah it apparently common
But its ok
Yeah, it's a thing I'll just have to learn when I get one
Alright so this is where I am in my models...
# Models
class UserAccount(db.Model):
"""
Account Holding User
"""
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default="static/default.jpg")
password = db.Column(db.String(60), nullable=False)
account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
agree_over_18 = db.Column(db.Boolean, nullable=False)
def __repr__(self):
return f"User('{self.id}', '{self.email}'>"
class PlayerProfile(db.Model):
"""
Each user gets a player profile with which to make characters
and save progress in various Campaigns
"""
id = db.Column(db.Integer, primary_key=True)
It doesn't really make sense to have the primary key be another id when the PlayerProfile is essentially an extention of the UserAccount -- the only reason I have them as different models is because there are different types of profiles, for the Game MasterProfile (the person who writes the campaign) and its just easier to separate into different places.
But I'm not sure how connect them in the most normalized way.
Is this maybe a question for #databases ?
Or does it?
I guess the ids dont have to match
its not like they will be front facing
and while every UserAccount will have a PlayerProfile, not everone will have a GameMasterProfile
So I will have to get used to those ids being not the same anyway
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship GameMasterProfile.campaigns - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
So relationship needs a foreign key. I dont really get this entirely. You need a ForeignKey and a relationship
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
So it basically just seems like like every Foreign key needs an inverse relationship line from the model it comes from
Just having OneToOne, OneToMany, and ManyToMany would be bae af
So this is the most updated version
class UserAccount(db.Model):
"""
Account Holding User
"""
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default="static/default.jpg")
password = db.Column(db.String(60), nullable=False)
account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
agree_over_18 = db.Column(db.Boolean, default=False)
player_profile = db.relationship('PlayerProfile', backref="player", lazy=True)
def __repr__(self):
return f"User('{self.id}', '{self.email}')"
class PlayerProfile(db.Model):
"""
Each user gets a player profile with which to make characters
and save progress in various Campaigns
"""
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user_account.id'), nullable=False)
user = UserAccount.query.get(1) >>> user User('1', 'asdfasfsd@asdfdsfds.com') >>> user.player Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'UserAccount' object has no attribute 'player'
What am I doing wrong?
>>> user_player = PlayerProfile()
>>> user_player
<PlayerProfile (transient 139645120491088)>
>>> db.session.add(user_player)
>>> db.session.commit()
Traceback (most recent call last):
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: player_profile.user_id
[SQL: INSERT INTO player_profile (user_id) VALUES (?)]
[parameters: (None,)]
OneToOne. It's a pretty awesome idea.
Just cant figure out how to do it.
try
user_id = db.Column(db.Integer, db.ForeignKey('useraccount.id'), nullable=False)
PlayerProfile requires a UserAccount id,
id = 1
new_player = PlayerProfile(user_id = id)
db.session.add(new_player)
that causes it to error at creating a new user.
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship UserAccount.player_profile - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
I think user_account is the table name that it would build based on UserAccount class. I could specify the table name I think by __table__ = 'user_account' to be sure
I got it to save a user and player.
By giving it an id like you said, specifically the id of the user.
But I still cant do user.player.some_player_prop
Which is what I need
I think this has what i need
I really wish this was the Django ORM lol
https://stackoverflow.com/questions/3464443/sqlalchemy-one-to-one-relationship-with-declarative/9611874#9611874 or this is better
yeah I'd double check your table names
For the relationship in sqlalchemy you're looking for you must specify BOTH a relationship attribute, and a separate linking ID attribute which is a foreign key
It will the (attempt) to link the two properties together for you
Thank you, that sort of makes me fee like what Ive come to is going to maybe work
class UserAccount(db.Model):
"""
Account Holding User
"""
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default="static/default.jpg")
password = db.Column(db.String(60), nullable=False)
account_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
agree_over_18 = db.Column(db.Boolean, default=False)
player_profile = db.relationship('PlayerProfile', uselist=False, back_populates="user")
def __repr__(self):
return f"User('{self.id}', '{self.email}')"
# def __init__(self, **kwargs):
# super(Foo, self).__init__(**kwargs)
# # do custom stuff
class PlayerProfile(db.Model):
"""
Each user gets a player profile with which to make characters
and save progress in various Campaigns
"""
__tablename__ = 'player'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('UserAccount', back_populates="player")
def __repr__(self):
return f"PlayerProfile({self.id}, {self.user})"
I'm about to test this, but I have to take a shower real quick. I'm going to enjoy the time in the shower believing that this will work.
I have to say if that is the correct way to do it, that is overly confusing. I need a better ORM lol
You shouldn't have the "player_profile" relationship
back_populates should create a "player" attribute on UserAccount for you
If you need to put a relationship there, it should match, so be put into an attribute named "player" and back_populate user
as it is now it has two names, which might break the pairing
I'll try both. I was copying from this basically https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html#one-to-one
I don't actually know what back_populates or uselist even mean. The other keyword args im pretty familiar with
"back_populates" refers to the reverse of the property--so, for PlayerProfile.user, it would be UserAccount.player (like you have above)
I'm pretty sure "uselist" means that it will use a list representation rather than a set
I see.
Welp, that's not right
the uselist flag indicates the placement of a scalar attribute instead of a collection on the βmanyβ side of the relationshi
so basically, one to one instead of one to many
Its weird that they dont just use those terms which im more familair with but im sure once i learn this it will be nothing
It is a weird name that makes me want to double check my own code
So, for clarity:
class Dog(db.Model):
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integger, db.ForeignKey('owner.id'))
owner = db.relationship('Owner', back_populates='pets')
class Owner(db.Model):
id = db.Column(db.Integer...)
dogs = db.relationship('Dog', back_populates='owner', uselist=True)
is for a many-one, one owner, many doggs
The two are linked in the database via the owner_id foreignkey, but linked in python via the owner <-> dogs relationship.
If, for whatever reason, each owner could only have one dog, you'd change the uselist on dogs to false so that it knows there can only be one
Since in the database, many dogs technically could have the same owner id--but unique=True on owner_id in the Dog model could work
That is, to say, the columns generated by my example are:
Table Dog:
id | owner_id |
1 | 1
Table Owner:
id |
1 |
Oh, cool thanks for writing this out. Let me catch up.
and accessing Owner.get(1).dogs generates something like:
SELECT * FROM dogs WHERE owner_id = 1
You differentiating between python and the db helps me understand the difference
I think I get it now.
Thats why they gave you the helper role haha
So you essentially always use uselist on the 1 end
If I remember correctly, models have an _metadata attribute you can use to actually print out their table representations
what a terrible name for that kwarg
yeah
Ah, it's just .metadata, and it has all the tables for the current database via metadata.tables. Each model also has __table__ as well
Right so, it gave me this error when I tried the code above as is
sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class UserAccount->user' has no property 'player'
I'm going to try to remove the one you suggest as opposed to that one.
player_profile under UserAccount that is, I'll try it with that commented out
So something like:
for table in Dog.metadata.tables:
print(table.name)
for column in table.columns:
print(column.key, column.type_)
( Not sure if this works )
yeah it doesnt like this
sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class UserAccount->user' has no property 'player'
that is on attempt to instantiate a UserAccount.
btw
I'll snippet save that so that I remember that. Right now I have nothing in my tables haha 
So I guess it has to be double sided then >.<
Well even with both of them it doesnt like it.
What are you trying to do TLS?
What's the error (assuming the names match)
They need to point at each other, eg, one assigns to "player" and backrefs "user", and the other is assigned to "user" and backrefs "player"
backref is another word I dont really get. How is that different from back_populates
I'm trying to get have a User Account have a one to one relationship with a Player Profile.
sorry, I meant back populates there
backref is a different syntactical way of doing it
ah okay, so now might be a good time to just learn all the meanings of these kwargs
Because Im literally just copying other peoples code and being like, "uh, ok"
What's your current code?
Current code:
https://paste.pythondiscord.com/ebifapuroy.py
The place where Im having trouble is that it either...
on instantiation of one of these objects...
>>> user = UserAccount(email="me@mail.com", password="password")
Traceback (most recent call last):
...
sqlalchemy.exc.InvalidRequestError: Mapper 'mapped class UserAccount->user' has no property 'player'
or... before I got here, the problem was that though I could instantiate a PlayerProfile and a UserAccount I had no way of accessing one through the other.
ie
user.player.some_player_prop = "this"
I think Im going to spend some time reading the docs.
player_profile = db.relationship('PlayerProfile', uselist=False, back_populates="user") needs to be changed
user = db.relationship('UserAccount', back_populates="player") because this here wants it to be named player not player_profile
or well, you could change the second one to match, they just need to be the same
Ahhh
^^
soo...
as opposed to user = db.relationship('UserAccount', back_populates="player")
should it be user = db.relationship('UserAccount', back_populates=player_profile)
then? Or literally the variable name as a string passed to back_populates?
literally the variable name as a string passed to back_populates
weird
It's so that sqlalchemy can look at the class and figure out where to attach to
You tell it to initialize the models, and it goes through all the defined model classes and their attributes. Each class gets assigned a single table (usually), and each attribute that's defined as a column a column with a type and name. Then it sets up the code it needs to fetch across properties--so you can do, say user.profile, or profile.user and keeps track of them, and (might check them?).
Whenever you create/query for an object of that class, it eagerly goes and fetches the related objects with an extra SQL query. When it does so, it attempts to put them in the list/attribute that was specified in the relationship--so that in all cases where you have a UserProfile, it's .player attribute has a PlayerProfile already present. If the attribute doesn't exist, it throws that error
Should I have the primary key of PlayerProfile be a new id?
Kind of unrelated but
Is that the most normalized way to do this as a 1to1
You could, but it really depends on what you're doing
Why do you need two different models in the first place?
GameMasterProfile is another type of profile for creating the campaigns that players can join, and users can be either/or/both
Oh
Then I think the best case would be using the foreignkey column as a primary key as well
Thats what i was thinking
It should be as easy as removing the id column from PlayerProfile and adding primary_key=True to the user_id foreignkey column declaration
right
That enforces single-key single-concern, and probably also uniqueness per user
Thats how it should be
Thanks guys, its working
I'm gonna check out that table display script you had when I have some data in these.
π
It just displays the details... probably.. not the actual data, but I'm sure you could work it to the data too
ohh, just the fields on the table? Still, thats good to know.
I'm going to have to study this syntax before I really understand how to write these from memory
Do you find yourself referencing docs to do your models?
Even once you know it well
I don't use sqlalchemy often enough to memorize the api properly
just the pain points
but if I did I'd be able to remember it
you're using flask-sqlalchemy though, so the api is slightly different i think
yeah. the code looks nicer with normal sqlalchemy it because you dont have to have db. in front of everything
So here is the one problem I have left
well, maybe thats optimistic but
>>> user = UserAccount.query.get(1)
>>> user
User('1', 'mail@me.com')
>>> player = PlayerProfile()
>>> player
PlayerProfile(None, None)
>>> player.id
>>> player.user
>>> user.player_profile
As you can see at the end, it creates the connection where something should be... but I'm not sure how to connect them.
I cant instantiate the PlayerProfile anymore with anything because all of its parameters are foreign
class PlayerProfile(db.Model):
"""
Each user gets a player profile with which to make characters
and save progress in various Campaigns
"""
__tablename__ = 'player'
id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, primary_key=True)
user = db.relationship('UserAccount', back_populates="player_profile")
It wont remain that way but I figure I need to get the relationship figured out first
user.player_profile = player might be as simple as that?
You should be able to instantiate it via PlayerProfile(id=user.id) or PlayerProfile(user=user)
ahhh I was using positional arguments like an idiot
Do you think its dangerous to use auto incrementing ids for users? Or no if they are not front facing at all?
Dangerous in the sense that users will be accessible from other data if I use those numbers in urls and stuff
Which I guess I answered my own question.
Well
Normally users shouldn't be able to access each other if you don't want them to by controlling access in general, so even if you do know a user id you can't get anything from it
but an autoincrementing user ID does leak how many user id's you have
In my opinion its often not a particularly important consideration, but if you are very concerned about security you should use uuids, yeah
I enjoy best practices in that regard but I will probably not focus on it atm
since everything is test data it doesnt matter
I went and refined that printer thing
for table in Base.metadata.tables.values():
print(f"Table `{table.name}`:")
columns = {}
for column in table.columns:
column_format = f"{column.key} ({column.type})"
columns[column.key] = column_format
print(f"{column_format:>6}", end=" | ")
print()
for obj in session.query(table).all():
for prop, column_format in columns.items():
print(f"{getattr(obj, prop):>{len(column_format)}}", end=" | ")
print()
print()
niceee
let me get the classes with it I forgot those
class Dog(db.Model):
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integger, db.ForeignKey('owner.id'))
owner = db.relationship('Owner', back_populates='pets')
class Owner(db.Model):
id = db.Column(db.Integer...)
dogs = db.relationship('Dog', back_populates='owner', uselist=True)
Paste, had a missing line
Here's the full working example:
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
Base = declarative_base()
class Dog(Base):
__tablename__ = "dog"
id = Column(Integer, primary_key=True)
name = Column(String)
owner_id = Column(Integer, ForeignKey('owner.id'))
owner = relationship('Owner', back_populates='dogs')
class Owner(Base):
__tablename__ = "owner"
id = Column(Integer, primary_key=True)
name = Column(String)
dogs = relationship('Dog', back_populates='owner', uselist=True)
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
# create a configured "Session" class
Session = sessionmaker(bind=engine)
# create a Session
session = Session()
# work with sess
bob = Owner(name="Bob")
sally = Owner(name="Sally")
spark = Dog(name="Spark", owner=bob)
session.add_all([bob, sally, spark])
session.commit()
for table in Base.metadata.tables.values():
print(f"Table `{table.name}`:")
columns = {}
for column in table.columns:
column_format = f"{column.key} ({column.type})"
columns[column.key] = column_format
print(f"{column_format:>6}", end=" | ")
print()
for obj in session.query(table).all():
for prop, column_format in columns.items():
print(f"{getattr(obj, prop):>{len(column_format)}}", end=" | ")
print()
print()
Produces this:
Table `dog`:
id (INTEGER) | name (VARCHAR) | owner_id (INTEGER) |
1 | Spark | 1 |
Table `owner`:
id (INTEGER) | name (VARCHAR) |
1 | Bob |
2 | Sally |
that is pretty cool.
I forgot you could pass sqlite:///:memory:
what is the declarative_base about
something flask-sqlalchemy does for you
It seems like it sets up the base class.
I see how you are using things that are in flask-sqlalchemy, like session and etc, from another source. Im sure thats how it all works under the hood.
Do you think I could start just using normal sqlachemy?
I think the code looks cleaner
I have heard people say if you are using flask to just use it so I did
If you like it you can use it
@native tide yes use sqlalchemy if you can
It's a bit of a learning curve but once you are over that, it makes everything way easier
It also takes care of sanitization for you
So no sql injection
Hrm. Nice. I will definitely look at it. I think while learning I will just do this so there are less curveballs, but I like the look of that code a lot better.
I think the biggest things flask-sqlalchemy provides is a good interface to flasks configuration and similar
But both are flexible, and flask-sqlalchemy basically does what I did internally for you when you create it anyway
yeah
ok so im just start learning html, why <img src="C:\Users\User\Desktop/SW1.png"\> doesnt create the image on the website? My html file is stored inside C:\Users\User\Desktop\Language\HTML\Playground.html btw
@turbid glen You don't close the img with /> instead just use >
still cannot
@turbid glen I'm gonna guess it's browser security not letting pages access assets from the user's (your) computer
ohhh make sense, since the picture works if i put the pic in the same file as the html file
how do i change it?
Are you using an online editor?
im using vscode with its live server
yes it works that way
if i put them in the same file, <img src="SW1.png"> this alone works
Yup
btw its better to put those image together with the html file right? like best practice
Optimally you should have a folder called static
which contains subdirectories
like css, img, js
to categorize your files
Np π
(reposting as buried)
Here is my conf file, in /etc/apache2/sites-enabled:
<VirtualHost *:80>
ServerName artybot.xyz
DocumentRoot /home/artemisweb/artemisweb
WSGIScriptAlias / /home/artemisweb/artemisweb/artemisbots/wsgi.py
WSGIDaemonProcess artybot.xyz processes=2 threads=15 display-name=%{GROUP} python-home=/home/artemisweb/artemisweb/venv/lib/python3.8
WSGIProcessGroup artybot.xyz
<directory /home/artemisweb/artemisweb>
AllowOverride all
Require all granted
Options FollowSymlinks
</directory>
Alias /static/ /home/artemisweb/artemisweb/main/static/
<Directory /home/artemisweb/artemisweb/main/static>
Require all granted
</Directory>
</VirtualHost>
However, when I attempt to access the website, it just times out. What am I doing wrong? I have recently purged and reinstalled apache2, and I'm using a django app in /home/artemisweb/artemisweb, called artemisbots with only one project, main. I can't find the logs.
Try posting this on #414737889352744971
OK tq
π
I could help if it was nginx
You might also try unix.
Those guys are more into that side of thing than the average person here.
I can help but I am in class rn
How can i run bash commands such as "touch, heroku create" etc. in Pycharm terminal in W10? I was able to run these commands in Pycharm in my old laptop which was using W7.
Have you tried running them?
If they worked on W7, they should work on win10
Of course i did. They aren't workin'.
Are you in the terminal or the python console?
Can you send a screenshot?
But neither "touch" nor "heroku create" works.
Hold on.
(venv) D:\Python Projects\Django\API\Stock Management>touch dafuq.txt
'touch' is not recognized as an internal or external command,
operable program or batch file.
What does echo %PATH% give you?
D:\Python Projects\Django\API\Stock Management\venv\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;D:
Git\cmd;C:\Users\Burak\AppData\Local\Programs\Python\Python38\Scripts;C:\Users\Burak\AppData\Local\Programs\Python\Python38;C:\Users\Burak\AppData\Local\Microsoft\WindowsApps;D:\PyCharm\bin;
;D:\heroku\bin
So, any ideas?
PEP8, I'm gonna need you to stfu
Haha
@jagged lark ?
So I want to use .login_view( from flask-login), but I am not reallt sure what I need to set in it, do I set the route or what?
You should ask #tools-and-devops, I have no idea Ksenofanex
This is what it says in the docs, I would be happy if someone could expalain what exactly is being set in the .login_view
Edit: Nvm, found my answer, had to enter the name of the route
@jagged lark Thanks.
Should i be using flask-login?
It is decent from what I heard
@short venture touch doesn't work on heroku because heroku dynos have non-persistent filesystem
so if you touch a file and restart a dyno, touched file will disappear
the main reason for that is non-persistent filesystem
pythonanywhere.com has persistent filesystem
i had the same problem
hey
i have flask project and i using flask_login and i want to add roles (admin,user,...) with permission in every view and can be change by client side is there good library ?
use django 
Hey, anyone has an idea on how to logout a user with oauth2 of discord using: https://discordapp.com/api/oauth2/token/revoke this url ? can't find any documentation on it
Hi I am new to web dev I am trying to make a tic tac toe game with flask
What is the best way to make the bored
easiest is a html table
Doesnt that sound pretty insecure to you, mjed?
@grizzled harness how about buttons
How do I input ???
X and o
code <div style="position:fixed; bottom:70%; left:42%">
<button>#</button>
<button>#</button>
<button>#</button>
</div>
<div style="position:fixed; bottom:60%; left:42%">
<button>#</button>
<button>#</button>
<button>#</button>
</div>
<div style="position:fixed; bottom:50%; left:42%">
<button>#</button>
<button>#</button>
<button>#</button>
</div>
Personally, I would learn how to make this first make python tic tac toe
https://pencilprogrammer.com/python-programs/tic-tac-toe-python/
They have plenty of others if you search python tic tac toe
The thing is, they are all going to be command line tutorials, and almost anything you find on making a web tic tac toe is going to be in JavaScript. As much as I usually say JavaScript is over used, this is a situation where it might be pretty called for.
But if you're just trying to teach yourself Flask and Python with a practice project, it can be done, and it will work very similarly to the command line version. If you learn that first, as much as you may want to skip it, it will make all of this easier for you.
After you understand that, you'll basically do it the same way. You wil store which is X, O, or unselected in a data structure. You'll have the same code that determines how the board should be displayed.
The main difference will be that instead of rendering in command line, you'll be sending the data from a view to a template and generating that HTML line by line based on the state of the game.
I hope that helps. I will add that this is an unorthadox use of Flask but it can be done.
You'll have to send a POST request back with each submit. There is a submit type. Look into forms and POST requests in html
@native tide I already made a tic tac toe with minimax algorithm
@solar hatch you need to make each cell of the board a button
and then take actions using js
js what about python@rustic pebble
You cant use python client-sided
You can do it... But it will involve each button sending a post request.
Still don't
Yeah, imo...
I usually dont agree with Kiwi about when to sue Javascript
But here they are right
You will also need to implement a way to determine which button is which
I usually dont agree with Kiwi about when to sue Javascript
@native tide β€οΈ
If you really are set on doing in Python just to do it
And then load the server x9 for each player
Know that it involves sending post requests to the server and then doing the figuring out of what the state of the game is
right
You can refresh by redirecting in flask
But yeah
JS is better suited for something like tic tac toe.
oh right
cool
@solar hatch if you need help ping me here
Sure
<form action="#" method="post">
<div style="position:fixed; bottom:70%; left:42%">
<button>{{hello}}</button>
<button>#</button>
<button>#</button>
</div>
<div style="position:fixed; bottom:60%; left:42%">
<button>#</button>
<button>#</button>
<button>#</button>
</div>
<div style="position:fixed; bottom:50%; left:42%">
<button>#</button>
<button>#</button>
<button>#</button>
</div>
</form>
!code
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
β’ These are backticks, not quotes. Backticks can usually be found on the tilde key.
β’ You can also use py as the language instead of python
β’ The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
You need trigger actions
with buttons
Button can have an attribute called on-click and an attribute called id
on-click should call a js function which saves the user input
Do you have a server set-up?
Flask server right?
yea
@native tide You can take it from here
Or radio
To be honest...You're going to have to spend some time learning HTML forms before you can do this. Im not going to walk you through doing this. But I can tell you that before you can do this you need to learn HTML forms and POST requests.
then diverse each key into different ifs
ok...i get it when i need help i will ask
wooow
π
π
I was able to jump into web apps from python because I have strong background of CSS and HTML.
If you really want to excel at doing web apps, you should take the time to do that.
its not as hard as a programming lang
is it best practise to use only one <h1> inside one html file?
heard from the website
hehe
Im not sure how much that is a rule or not, but it sounds like it makes sense. The idea of the h1 is to be the main title.
So I would say that yeah.
i heard using too much h1 ruined your "reputation"??
I was able to jump to websites cause I decided it
what concept does discord web uses?
i know ajax and ws is a thing but how does it load a new "page" with a new url in the address bar but not trigger the refreshing?
I'm pretty sure it doesnt load new pages.
@wet ibex
Discord web and discord app are the same
They are based on technologies like electron
the indent in html is kinda confusing compare to python
i think i kinda get it
It is native app with refreshing elements
but i wonder how to implement the same amount of interactivity without traditional page reloading 
not possible with pure html/css/js?
I dont think so
Look up single page application.
And js is pure before ES6
ES6 introduced like 1000 new things
Single page applications can do roughly as much as traditional desktop apps - they just can't interact with the underlying PC as well. They are generally pure HTML/CSS/JS on the client side though
Why not use frameworks?
nah im just new to using them
Well, React is pure js in the same way the Flask/Django are pure Python
any opinions on using which frameworks together with django?
im new to angular/react/vue
If you want SPAs, then I'm not sure Django is the way to go
huh
React + Flask is good
in general, React or Vue seem the nicest
i just want to make my dashboard not reload rip
Vue is simple and straightforward, React is the real deal
I think most people who rely on server side rendering tend to not rely as heavily on JS. They sprinkle it in and tend just do everything they need JS for in vanilla.
Theyre all fads that are going to be dead in less than three years lol
That shouldn't be too difficult. You just make a REST API backend, and use React/Vue on the frontend
Nah, React is probably gonna stick around relatively long term
we're at the point where most other frameworks are following some amount of Reacts ideas
But if you want really good and efficient apps
Well i dont know anything about the js frameworks other than that they fall out of favor as quickly as they rise
GraphQL + AIOhttp is good
interesting how no one talks about angular
and its becoming the de facto solution at a lot of places
but you might be right
That has been true with a fair few of them - and it could be true for react - but I think React will probably stick around
Angular is the other major framework, but they made a lot of mistakes that React aren't
Charlie, have you used graphQL?
namely massively changing things
I've used it a tiny bit, and it seems pretty pointless
its just a new way of interacting with RestAPIs
But its not currently difficult to interact with Rest APIs
The most common use of GraphQL is to collate Rest endpionts
I plan to get back to React when I have an idea thats good for REact. What Im working on now is a document based application that just is better the way im doing it with server rendering and definitely there will be vanilla JS somewhere. But its a website for fiction. shrug. It doesnt need to be an SPA.
But when I get that idea Ill do it.
HTML forms typically have 1 button.
<form action="/action_page.php" method="get" id="form1">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname">
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
Thats an example.
What you're trying to do is doable, but its unorthodox and is going to be hard for you. You're trying to learn Flask, Post requests, html forms, all this stuff... which a project that makes all of that stuff more complicated than it needs to be.
You could do this project
function tictactoe(action){
if (action = 'youraction identifier'){
}
}
then you just makes 9 ifs
But you need to learn HTML, http methods and responses, etc
I wont walk you through
Like...
andyou can just do for each button
<button onclick='tictactoe(clickidentifier);'></button>
Ive never understood the type of person who throws themselves into project that is above the things they know.
That is exactly how I learn @native tide
For example, when I started learning Django, I made a blog site I didnt even intend to use.
Haha
Because thats the stereotypical Django app.
so any other project ???
If I had gone into Django trying to use it to make tic tac toe lol
easy
I would have never got anywhere because I wouldnt have understood HTTP stuff and talking to the server
andyou can just do for each button
<button onclick='tictactoe(clickidentifier);'></button>
@rustic pebble I think it is better do add an eventListener
@rustic pebble A lot of people do. I dont get it myself
@vivid cosmos that is the easiest way, but how will you explain eventListener to someone who doesn't know the basics of js
onclick is self-defining
Yes, a webb portfolio is much easier. Personally I just follow tutorials doing other peoples projects until my own ideas start to pop out.
@rustic pebble A lot of people do. I dont get it myself
@native tide I just do it, I find an idea and try to find the manners to implement it
yea...i will make a port folio app for myself
Well, if that works for you, thats great...
But if you're going to be that person, you cant show up in chat being like, "How do i..."
I do deep research
π
But thats what im saying, if you dont know what you're doing
You have to teach yourself basic boring things first.
And then I just ask with what I have
If that works for you then it clearly does.
If you understand one language in a level which you can make pretty much anything that comes to your mind
Then every other language automatically becomes 10 times easier
It is way different knowing exactly what you want to do and just having a problem with the means
for example
That's true, but... when what you need to learn is basic HTTP protocol;
You have to start with that.
If you want to push an item in a list on python you do listname.append(itemname) on js you do listname.push(itemname)
Same thing different manners
HTTP should be pretty simple tolearn
That's true. It is like that and you eventually do become able to do it.
You would be surprised.
The average person doesnt realize the communication that goes on between a client and server
with headers and responses
I might sound haughty but I somehow never had to read the basics like how does http work, how does js control elements
Im just saying that... you can learn to make a post request thats a thousand times simpler than having 9 different possible ones you could make to play a game.
And then once you understood you would be like
I somehow knew it by myself
That is true
But tbh we are here on web-development to help people like that. I love it when someone who doesn't know much comes here and they leave with a happy face
Because that is how I sometimes felt on stackoverflow
But they kill newbies there
@solar hatch Not really, @shadow hornet has a good one let me see if I can find it
π
How do I enable https on Flask with SocketIO?
@green echo You are talking about enabling it in a development environment right?
Oh, then you need an SSL certificate
You can get from here
You need to add it to your webapp
I take it you are using nginx?
How are you hosting the server?
Using my own router
yeah
There are bots running 24/7 and pinging random ips at random routes, executing exploit scripts, if one happens to hit your own ip and port, if one tiny hole exists in your system you are ruined
I just want to show my site to my friends which I know would do nothing to harm my pc
oh
OH
ffs
Yea that is what I thought when I found out
I hate the internet
You are gonna need to run it off somewhere else, there are hosts that you can rent servers for 2.5euros per month
ugh
rip
I am speed making a portfolio website
Lets see how fast I am going to finish it
I will make it dynamic so it adds the projects from my github
I have a web app deployed with Heroku, but my form is not submitting.
In my local environment it's working just fine (I'm using Flask-WTF), but it fails when I deploy.
Can anybody help me on that?
VocΓͺ e sua famΓlia na melhor localizaΓ§Γ£o de SetΓΊbal do Recife.
Not without a link to the source code
forms.py
class ContactForm(FlaskForm):
building_name = HiddenField('Nome do Empreendimento')
name = StringField('Nome', [DataRequired(), Length(min=3, max=100, message="O nome informado tem que ter entre 3 e 100 letras.")])
email = EmailField('E-mail', [DataRequired(), Email(message="Email invΓ‘lido")])
phone = StringField('Celular/Whatsapp', [DataRequired(), Length(min=8, max=15, message="O telefone informado tem que ter entre 8 e 15 numerais.")])
submit = SubmitField('Quero saber mais!')
class Meta:
locales = ['pt_BR']
routes.py
#...
@app.route('/manoeltavares', methods=['GET', 'POST'], host='maxiimoveis.herokuapp.com')
def manoel_tavares():
#...
# Form Handling
form = ContactForm(building_name=building_name)
if form.validate_on_submit():
contact_handler(form, building_name)
return thank_you(building_name=building_name, folder_name=folder_name)
@rigid laurel
Oh, I see, another bug because of the host parameter, damn, can get rid of that because if I do not place it, it will look for my staticfiles on www.maxiimoveis.com.br/static
Any ideas?
I'm not entirely sure myself - but with the source code no one would be able to help
Best solution to monitor traffic on ur web app (unique visits etc..) using flask
Question: Is there a way I can have styles under an if?
Like I want to add something like that
````if element_id == 'project_wrapper'`:
#style```
i had something like different color of headers based on if statement
i did it in jinja idk if that helps u
Nah I dont want to make it that dynamic
Very ClichΓ© question. Iβm trying to make a social media like Twitter/Instagram and I want to use python/Django for some backend stuff. I donβt know anything about backend. Does anyone have any advice on where I should start ? I do know about frameworks and things like AWS but I donβt know how to use any of them.
If possible can anyone go into detail on what Instagram would specifically use Django for
My advice would be to follow the official django tutorial and docs, it's complete enough to give you ideas of how to do what you want to do
How can I serve images from my flask backend to the frontend?
Ideally I want to add them here, with js of course
Basically instead of setAttribute I want it to display an image
Oh nvm I found it, I will convert them to base64, send them over with http request, and then just add them as src for an html img
using the built-in bs4 decoder
@rustic pebble I parse them in my route and then use Jinja to render it in a for loop.
I want them to be dynamic
so only when a user clicks somewheree
an image gets loaded
Probably u want to use async requests then
I am using async requests xD
Cool then, u've everything figured out
this is my request for like one section
async function get_project_data(){
let url = '/data';
const response = await fetch(url, {
method: 'GET',
mode : 'cors',
cache : 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type':'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer'
});
let data = await response.json();
return data['Data']
}
I am having a problem
So I am loading the top left image
Statically through jinja
And the rest I am decoding through base64
the left one works
the others don't
Any ideas?
@native tide finally I used jinja
{% for item in data %}
<div class="box">
<div class="imgBx">
<img src="{{ data[item]['img']}}" width="100px" height="109px">
</div>
<div class="content">
<h2>{{ item }}</h2>
<p>{{ data[item]['description'] }}</p>
<a href="{{ data[item]['url'] }}">Read More</a>
</div>
</div>
{% endfor %}
haha
I couldnt do it without it
http://campanhas.maxiimoveis.com.br/laguna
When I submit the form accessing it through my alias_host it first redirects to app_domain and I have to submit it again in order it to proceed.
Any ideas why I have to submit the form twice?
__init__.py
#...
app = Flask(__name__, host_matching=True, static_host='maxiimoveis.herokuapp.com')
#...
#...
app_host = 'maxiimoveis.herokuapp.com'
alias_host = 'campanhas.maxiimoveis.com.br'
#...
@app.route('/laguna', methods=['GET','POST'], host=app_host)
def laguna():
#...
form = ContactForm(building_name=building_name)
if form.validate_on_submit():
contact_handler(form)
return thank_you(building_name=building_name, folder_name=folder_name)
#...
contact.html
#...
<form method="POST" action="{{url_for(request.endpoint, _external=True)}}">
#...
P.S: I'm using FLASK-WTF
VocΓͺ e sua famΓlia na melhor localizaΓ§Γ£o de SetΓΊbal do Recife.
@sly canyon I faced that problem some months ago, I never found out how to fix it so I used js to submit the form
@rustic pebble Can u paste your POST script 4 me?
I think it has to do with the flask routing
I unfortunately can't but I can build it for you
Could you send me your html form?
It is not that hard
@sly canyon
contact.html
{% from "forms/_formhelpers.html" import render_field %}
<form method="POST" action="{{url_for(request.endpoint, _external=True)}}">
{{ form.hidden_tag() }}
<!-- Name -->
{{ render_field(form.name) }}
<!-- Email -->
{{ render_field(form.email) }}
<!-- Phone -->
{{ render_field(form.phone) }}
{{ form.submit }}
</form>
_formhelpers.html
{% macro render_field(field) %}
<div class="{{ field.name }}-wrapper">
{{ field.label }} {{ field(**kwargs)|safe }}
</div>
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
ok you are going to need to add some ids to the inputs
If you want the form code rendered
give me the form rendered
U can see it on the page
sec
VocΓͺ e sua famΓlia na melhor localizaΓ§Γ£o de SetΓΊbal do Recife.
@rustic pebble I think I found a opssible solution
I take it its this?
<div class="contact-form" id="contact-form">
<div class="form-header">
<p>Apenas uma unidade. Garanta jΓ‘!</p>
</div>
<div class="form-body">
<div class="text">
<p>
O bem-estar de viver em uma das Γ‘reas mais privilegiadas da Zona Sul do Recife te espera.
</p>
<span class="bold">Preencha o formulΓ‘rio e aguarde nosso contato.</span>
</div>
<div class="contact-form-wrapper">
<form method="POST" action="http://maxiimoveis.herokuapp.com/laguna">
<input id="building_name" name="building_name" type="hidden" value="Laguna">
<input id="csrf_token" name="csrf_token" type="hidden" value="IjFkYTFhZjExNjkwNzdjOWEzNzdlN2JlN2YzYmNlMDRkYjllZDJmYmQi.XnLFig.nD0YV_e9jey41caYP9Iq0UrRYqk">
<!-- Name -->
<div class="name-wrapper">
<label for="name">Nome</label> <input id="name" name="name" required="" type="text" value="">
</div>
<!-- Email -->
<div class="email-wrapper">
<label for="email">E-mail</label> <input id="email" name="email" required="" type="email" value="">
</div>
<!-- Phone -->
<div class="phone-wrapper">
<label for="phone">Celular/Whatsapp</label> <input id="phone" name="phone" required="" type="text" value="">
</div>
<input id="submit" name="submit" type="submit" value="Quero saber mais!">
</form>
</div>
</div>
</div>
Oh
Then we have totally different problems
Haha
By default some http requests from paths that aren't the host
are denied
If I enable it, do I still have to do the post request through javascript?
I hope so, will read the docs
You dont need much
You just do:
from flask_cors import CORS
CORS(app)
@sly canyon
I'm still reading the docs, doesn't seem like those two lines are enough in my case
I've tried the @cross_origin() decorator and I'm getting
NameError: name 'cross_origin' is not defined
Meaning that my routes.py doesn't know anything about CORS
doing CORS(app) is like applying CORS globally
so everything else you do is just a sub-case
@agile solstice You have posted it 3 times in total and one more here, total 4. Wait for someone to help you.
@rustic pebble
Indeed, I'm unable to achieve it even though I've activated CORS :/
Maybe that has to do with CSRF
Think I'll have to go with javascript
But I'm using FLASK-WTF
Give me a sec cause I am making my portfolio page
Sure
and I am in a crucial css point
Ok @sly canyon
I guess what I sent earlier is the actual code for the contact form right?
ok let me concatenate it a bit
<form method="POST" action="http://maxiimoveis.herokuapp.com/laguna">
<input id="building_name" name="building_name" type="hidden" value="Laguna">
<input id="csrf_token" name="csrf_token" type="hidden" value="IjFkYTFhZjExNjkwNzdjOWEzNzdlN2JlN2YzYmNlMDRkYjllZDJmYmQi.XnLFig.nD0YV_e9jey41caYP9Iq0UrRYqk">
<div class="name-wrapper">
<label for="name">Nome</label> <input id="name" name="name" required="" type="text" value="">
</div>
<div class="email-wrapper">
<label for="email">E-mail</label> <input id="email" name="email" required="" type="email" value="">
</div>
<div class="phone-wrapper">
<label for="phone">Celular/Whatsapp</label> <input id="phone" name="phone" required="" type="text" value="">
</div>
<input id="submit" name="submit" type="submit" value="Quero saber mais!">
</form>
so
What you sent is the flask request form
I will make a script which on submit sends a json with all the data you need
Btw the data you need is:
building name
csrf_token
name
email
phone
Correct?
I don't need the csrf_token actually
I've done it before, but I forgot how to do it, long time without touching code :P
async function send_contact_form(){
let url='/laguna';
let build_name = document.getElementById('building_name').value;
let name = document.getElementById('name').value;
let email = document.getElementById('name').value;
let phone = document.getElementById('phone').value;
let response_data = {'building_name':build_name, 'name':name, 'email':email, 'phone':phone}
const response = await fetch(url,{
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no=referrer',
body: JSON.stringify(response_data)
});
return await response.json():}
Change the submit button to this:
<input id="submit" name="submit" type="submit" value="Quero saber mais!" onclick='send_contact_form();'>
To access t he data on the backend you would do normally what you did with form but using the following
@app.route('/laguna', methods=['POST'])
def get_contact():
data = request.json
build_name = data['building_name']
name = data['name']
email = data['email']
phone = data['phone']
@sly canyon
This won't check if the fields are empty or not
@rustic pebble Thanks, will try
This works 99.99%
Hey guys. I am a newbie and I got an assignment to do I just don't understand this one thing.
I know username of user and Post model with share foreign key with contrib.auth.User model.
But don't how it will effect the databases
@cobalt oyster look at this example https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/08-Posts/flaskblog/models.py
@weary arrow thank you. But I haven't used flask I use Django and in Django the migrations takes care of database. So I am having trouble understanding how I can give foreign key relationship only on model level.
why the video i put on my website with iframe said "video unavailable"
!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.
β’ Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
β’ 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.
β’ Be patient while we're helping you.
You can find a much more detailed explanation on our website.
<iframe width="560" height="315" src="https://www.youtube.com/embed/nUtgOwCh2uY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> and <iframe width="560" height="315" src="https://www.youtube.com/embed/ct8In_FAvZE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
copied the embbed code directly from youtube, first code works fine after playing the video
second one instant go 'video unavailable' after clicking play
I have flash messages in my app but for some reason when ever they are displayed, they are displayed with a distance from a top, any ideas on wjat cpuld be causing something like this?
@turbid glen Not to sound offensive, but have you considered the possibility that the video is actually Unavailable
I make a div
with class namefooter
and add this
.footer {
padding-left: 2rem;
padding-right: 2rem;
display: flex;
align-items: center;
justify-content: space-between;
}
Im sure i copied the code correctly from the video. I googled a bit and if the user locked the video, it will appear as in the picture. But its not in my case so
Actually I usually have it like that
So my css lookslike that
@solar hatch
.footer-sep {
margin-left: 2rem;
margin-right: 2rem;
margin-bottom: 0;
margin-top: 1rem;
border: 1px solid #3f3f3f;
}
.footer {
padding-left: 2rem;
padding-right: 2rem;
display: flex;
align-items: center;
justify-content: space-between;
}
Hmm
@turbid glen There are some times where YouTube bugs out
When you get this it probably means it has been disabled for viewing outside youtube
Yea
It depends on your css layout, but usually you could do either of those
