#web-development

2 messages ยท Page 50 of 1

tired root
#

change it to 50%

native tide
#

flex: 1 1 var(--pixels)px; are those good defaults to start with? Not sure I understand what the first two are affecting yet. I know its grow and shring.

btw is that legal css with the var() .. I noticed that it works sometimes when I do it and not always

tired root
#

I never use var tbh

native tide
#

ah, I love them

#

for color values and numbers i use a lot.

#

This is exactly what I need to make my damned thing i was making earlier.

#

I was resorting to just... stuffing classes and properties to make things match.

#

Then media querying when they dont work at a size

#

I settled for "forgot" because everthing longer than that took up too two lines of space for some reason

#

I'll probably move it down below later. tired of fiddling with it.

tired root
#

put it as a link below the login button, spanning the width of the form

#

does not have to be a button

native tide
#

yeah, that's how it originally was. I was just playing with different things earlier with it. I learned some stuff but I also learned that I need to learn some more stuff. I put those things in at least 6 different arrangements trying out bootstrap classes in various combinations. ha. It ended up being the simpler approach was better.

#

I got a random question. How would you approach this. This is a screen cap of me zoomed out in my browser to demonstrate the experience of people with the modern absurdly large resolutions of today.

How would you go about checking that the size of the screen is pushing the top menu too far to the left and then push it back the other way so that its more aligned with the header?

Or do you think its fine like that? I dont use that large of a res anyway but people do.

#

It has something to do with a position setting and coordinates im sure

#

Also my colums are not spaced equally because I am fixing them ha

tired root
#

I am trying out flask-socketio

#

i don't get it

native tide
#

is it like normal socket on flask?

tired root
#

It's weird for sure

#

It says: The application must serve a page to the client that loads the Socket.IO library and establishes a connection:

#

But it does not load my template

#

so there is no connection being made

#
from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)


@app.route("/")
def index():
    return render_template("index.html")


if __name__ == '__main__':
    socketio.run(app)
native tide
#

the only thing ive really ever done with sockets is open them, listen on ports for transmission, and receve them from another script haha. Good luck

#

how do i stop elements from overlapping eachother when i shrink my browser?

tired root
#

give me a fiddle with the problem @native tide

native tide
#

what? @tired root

tired root
#

a minimal example using jsfiddle

native tide
#

flex, grids, media queries, and possibly by using bootstraps col system if you cant figure those out.

#

But yeah. That.

tired root
native tide
#

what do i do with the fiddle?

tired root
#

You make a minimal example that illustrates your issue

#

css and html are way too complex to give you an answer based on your previous question

native tide
#

oh ok

#

sorry, pretty new to this

#

yeah, you just copy your html yo html part, the css to the css part

#

and then click save

#

you get a url and show it to use

#

can't i jiust send my html and css here

#

Then someone would just be having to make fiddles for you. Might as well learn to do it.

#

sorry

#

its all good

#

its like pastebin

#

cool

#

Im gonna take the time to master this flex and grid stuff before I sink away a lot of time just tinkering with what css I know. There are too many conditions for things to go wrong to not approach it with perfect best practice i think

#

im tired of the one little thing that i cant figure why it does that.

#

So im learning this stuff.

#

It seems more robust than cramming properties everywhere.

#

@tired root any luck?

tired root
#

about what?

#

If you mean the fiddle, I don't see anything overlapping there

native tide
#

if you resize, his content is covering up his bio link

tired root
#

resize which way?

#

The document is also missing the opening <html> tag

native tide
#

But its maybe going to get you started ...

#

i put that html tag iin there for you

tired root
#

The whole css is also only using static sizes

#

Which is bad when you deal with different screens

heady ore
#

Hi, I'm the django beginner. I want to know how to let the pdf file show on the webpage. I have a index.html that can show the content: title, abstract, year and others so far. And I've made the title became clickable to another web address. But how can I create a new page for this address and showing the pdf content? Thanks
PS. I have a sql table storing the pdf file path.

tired root
#

@heady ore Use pdf.js

heady ore
#

is there anyway that is wasy to do that? I dont have any experience in front end

#

so it might be a huge gap

tired root
#

That is the easy way

heady ore
#

so I think the first step for me is: create a page that shows the file_path after I click the title

#

but actually I dont really know how to start

tired root
#

Showing the file path on the server isn't a very good idea

#

The question is, what you want to do here

#

if you want to display a pdf in your web page, use pdf.js

heady ore
#

i know. but at least it allows me to link two sql table

#

i dont know how to do this yet

tired root
#

This does not make any sense

native tide
#

I should learn transition

#

the css prop

tired root
#

How does displaying a pdf make you "link two sql tables"?

heady ore
#

i have two tables. one has the info of doi, title, abstract and others. another has doi and file path, the doi is the foreign key

#

so now i only able to show the content from the first table

#

and want to know how to link to another based on doi

tired root
#

Use a sql select with a where statement

#

SELECT doi, file_path FROM tablename WHERE doi=?

heady ore
#

i know how to do that in sql command, but how can i implement that in django?

tired root
#

or use a inner join on the first query

#

what are you using as a database connector?

native tide
heady ore
#

I use postgresql

native tide
#

the models system is the most useful thing about django, there is an entire ORM for interacting with a database. You run queries through python after setting up your models and then merging to your database. Then you can use those queries in logic (usually under views.py) where you can send context (variables from the logic) to the template to render however you wish.

#

not sure if django is the part that you are struggling with or if front end.

heady ore
#

actually, both. I know how to get data from api, sql, mongo, selenium. but haven't known deeply in django.

native tide
#

yeah... i had to construct the polls app (documentation tutorial) and then make corey scahfers django class blog project before it really started to click. It is so big that its overwhelming. But it just takes reading and then doing.

#

It is very different from anything i had done before as well.

#

And tbh

#

I still dont know all the intricate details of django. I know the basics.

#

There is too much to know, you basically have to work with it for a long time to be very versed with it

#

basics are not too bad though you just need to read the docs

#

if the HTML is the hard part for you... might want to do that as well. Templating engine isnt very powerful without it

heady ore
#

too many things to know to build with django

native tide
#

I would say web dev is generally like that I think no matter what you get into it. And probably all dev really in a way.

#

sigh

#

css is some hacky bullshit sometimes. Ive probably been doing it for too long. need break

heady ore
#

should i put the sql command in views.py?

tired root
#

what do you mean with host?

#

as in, create a new vhost in apache?

#

I mean which address the website is running under isn't really the job of the framework

#

You need to elaborate on what you want

#

What are you using for publishing?

#

As in, server software

#

nginx, uwsgi, apache etc

#

Generally, a subdomain is the servername in the software you use and the sub domain also needs to be announced via the dns

fierce frost
#

How would I handle a Cyrillic string in Flask's flashed message?
It's complaining whenever I flash() a Cyrillic string

tired root
#

Yes, that is the A record

#

the IPV4 forward zone

#

Other records in DNS are ptr reverse zone and AAAA for IPV6

#

at the very least, you should have an IPV4 forward zone and a reverse zone

#

You need mod_wsgi for apache

#

yes

#

Which OS?

#

Debian derivative?

#

okay, that makes things simpler

#

go to /etc/apache2/sites-available

#

touch projectname.conf replace projectname with whatever

#

nano projectname.conf

#

or vi, I don't care

#

are you using tls?

#

lets'encrypt?

native tide
#

I dont have my test server encrypted but i also dont have a domain name... and its not open to the web. There is a thing called self signing but I dont really understand what the point of that is

tired root
#

It means there is already something running on port 80

#

Is there a nginx or so running?

#

yeah, well then you can't run a second webserver

#

You need to configure this with nginx

native tide
#

you can just stop nginx tho cant you?

#

i guess not if youre using it

tired root
#

Yeah, the question is if he is using it or not

#

as a mail frontend?

native tide
#

cant you serve on another port?

#

or listen on

tired root
#

nginx is running as a service dude

#

systemctl status nginx

#

ok, then lets setup django on nginx

#

since it runs on a subdomain, the mail can stay on :80

#

What do you want to use to run django? We can use apache and nginx as a reverse proxy or something like uwsgi and nginx as reverse proxy

#

either way, we need a middle man

native tide
#

i would nmap 127.0.0.1 on slightly unrelated not to see what you got open. Is it normal to run a mail server on port 80?

tired root
#

It's the web frontend

native tide
#

ahh

tired root
#

no mail server runs on 80

native tide
#

yeah

tired root
#

REmove apache, then use uwsgi and serve it on 127.0.0.1 and an arbitrary port above 1023

#

Then configure nginx to act as a reverse proxy

#

Which means, it fetches the pages from 127.1 from the uwsgi server and serves it to the user

#

I gave you the docs for uwsgi

#

I can't do it for you and I can't guide you step by step

#

you need to learn this stuff

#

HOw are you going to maintain it otherwise?

native tide
#

getting postgres up on a test server was the hardest thing i ever did i think. Its not that it was that hard really. Its that the things i didnt know prevented me from understanding what i needed to do. I finally figured that out though. I would love to be able to have one of my servers be actually online. But the only way i could do that would be dynamic dns and port forwarding and locking down my router and i just dont think im ready ha.

#

btw I just nmaped my localhost ip and then nmapped my specific local 192.168.x.x ip

#

What is the explanation for the variation going on with the open ports.

#

It was not what i expected and scared me at first but the not 127.0.0.1 address gave back what i expected to see

tired root
#

what variation?

#

@native tide

native tide
#

@tired root port 631 CUPS 2.2, port 3306 MySQL 5.7.29 1 service unrecognized despite returning data. If you know the service/version,

If I run the same command nmap -sV <ip> on my local ip, its nothing except what I expect to be there. But if I run it on localhost, there is stuff I dont know what that is (the stuff I named).

#

the fingerprint it cant identify seems to be my postgres server's open port.

#

To my knowledge im not running mysql on anything...

#

I might have um... I might have mysql workbench that i never use but tried out one time. Lets see. But still, why does it show on localhost and not literal ip...

native tide
#
<td>#{{lbcount += 1}} {{x.userid}}</td>

how would i do this in a flask template

#

cause += throws an error

#

its inside a for statement

quasi ridge
#

huh, you can't do += in flask? Odd

native tide
#

ikr

quasi ridge
#

well lbcount = lbcount + 1 might work

#

iirc those templating systems are separate languages that just happen to resemble python

#

but differ from it in surprising and annoying ways

native tide
#

expected token 'end of print statement', got '='

quasi ridge
#

๐Ÿ˜ฆ

#

maybe you can't do assignments inside a template? That'd be ... odd

native tide
#

damn

#

i just ended up doing loop.index

#
>>> u = UserAccount.query.first()
>>> u.email
'asdf@asef.com'
>>> u.email = "asdf@google.com"
>>> db.session.commit()

Is this all it takes to update the database?

#

Flask, SQLAlc

quasi ridge
#

@native tide Yeah afaict you can't do assignments like in python

native tide
#

Yea i dont like how you cant do alot of python related things in jinja templates

#

i had to define len() lmao

#

i was like wtf i thought that would atleast work

quasi ridge
#

there's another template language called "moustache" that I like (in theory; I've never really used it) because it doesn't even pretend to be a python-like language

haughty saffron
#

Is this how you would return a JSON response with an aiohttp server?
btw is this how you return a JSON response?

ok = {"status": 200, "error": None, "successful": True}

def json_response(_json: dict = None, status: int = 200):
    if _json is None:
        _json = ok
    return web.Response(body=_json, status=status, content_type="application/json")
quasi ridge
#

looks reasonable

native tide
#


    Association Proxy
    Automap
    Baked Queries
    Declarative
    Mutation Tracking
    Ordering List
    Horizontal Sharding
    Hybrid Attributes
    Indexable
    Alternate Class Instrumentation

shadow hornet
#

association proxy is useful for many-to-many relationships

native tide
#

echo $THAT >> notes.txt

shadow hornet
#

hahah

native tide
#

the names make it hard for me to tell what theyu are for

shadow hornet
#

yeah the names make them sound scarier than they are

#

a declarative system basically allows sqlalchemy to map classes to database tables

native tide
#

Does it not already do that? I was just reading about that one.

shadow hornet
#

it does that if you use the feature

#

you import the declarative base and create models with it

#

if you do that, then yes

native tide
#

What I mean is I have a models.py file with classes that become tables as far as I know. The only thing I use to make my models is db.Model, UserMixin, essentially db = SQLAlchemy(app)

#

the mixin comes from flask_login

#

But

#

I did just try to add a property to a class that the database did not have

#

and it did not like that

shadow hornet
#

add?

#

you can't do that

native tide
#

yeah, i know, i was gonna reinit the data

#

its all just test data

shadow hornet
#

ahh ok

native tide
#

drop everything

shadow hornet
#

yeah the database schema is set in stone

native tide
#

but does it not have ways to do that?

#

to migrate?

shadow hornet
#

if you change it, you have to do migrations

native tide
#

in django its easy to migrate

shadow hornet
#

because it's all built in haha

#

yeah django is like an all-in-one package

native tide
#

yeah, ive looked at those migrations py files

#

so

#

what is the manual process of migrating?

#

#databases or here? they might know a lot about that huh? but maybe not webdev orms

shadow hornet
#

i'm not sure about flask-sqalchemy, but for sqlalchemy, you'd typically use alembic

native tide
#

ive heard that from someone. Is migrating a task that is worrisome and liable corrupt data you care about?

#

i know that ideally you plan to not need to do that.

shadow hornet
#

yeah you typically don't want to do migrations too much, but it should not be too worrisome to do one

#

some practice on some dummy data and you should be fine

native tide
#

mm. I'm just not sure what the process entails. I suppose when I really wantto do it I will read up. Right now Im more interested in learning fundamental design done right from the beginning

#

I think im going to stop using sqlite and turn on my postgres server and see how much more difficult it is to work with it. Ive already done it with django. not sure how difficult it will be with this.

oblique hemlock
#

Hello

shadow hornet
#

good luck!

oblique hemlock
#

I have a domain name and I want to connect my flask server to run on it

quasi ridge
#

that's harder than it should be, in my experience ๐Ÿ˜

#

I've done it but it took time and $

oblique hemlock
#

Tell me how please :O

quasi ridge
#

well what I did -- certainly not the only way -- was I got an El Cheapo EC2 instance from Amazon AWS

#

got a static IP address (free, surprisingly); pointed the domain name at that address, installed nginx, figured out how to get that working, &c &c

#

Oh I think I only needed nginx because of SSL -- if you don't mind not using SSL, you don't necessarily need it

#

but you really should use SSL

oblique hemlock
#

I already have a server and I connected it to a dumb html page xD

#

It's working

quasi ridge
#

x l n t

oblique hemlock
#

I just want to know how to connect my flask to it

quasi ridge
#

so really you could run your flask app right now and it'd probably work

#

well what's the server?

#

apache? nginx?

#

in either case, they should have docs explaining how to use it as a reverse proxy.

oblique hemlock
#

Should I type specific thing in app.run?

quasi ridge
#

Or you could just shut that down, and run your flask app to listen on the same port (probably either port 80 or 443)

#

I have no idea

#

oh

#

maybe the port number

oblique hemlock
#

5000?

quasi ridge
#

up to you

oblique hemlock
#

So It's okay then

quasi ridge
#

if you use 5000, chances are your flask app can peacefully co-exist with your existing server

oblique hemlock
#

That didn't actually work

quasi ridge
#

you might need to do something special to allow incoming requests on that port -- in ec2, for example, you have to add an entry to your "security group"

oblique hemlock
#

Oh

quasi ridge
#

probably depends greatly on your hosting service

oblique hemlock
#

Debian

quasi ridge
#

I doubt that's your hosting service; that's probably just the linux distro you're using

oblique hemlock
#

I got you

quasi ridge
#

"hosting service" is "people who actually run the physical computer for you"

oblique hemlock
#

aws?

quasi ridge
#

I dunno

#

is your machine an ec2 instance? If so, then yes; that's AWS

oblique hemlock
#

It is

quasi ridge
#

ah there you go

oblique hemlock
#

lol no

#

we are with vultr
we have a VPS
a server

quasi ridge
#

no?

oblique hemlock
#

Sorry xD

quasi ridge
#

oh ok

#

well vultr might have something similar, where you have to explicily tell it "please allow incoming TCP/IP traffic on port 5000"

oblique hemlock
#

Yes

#

Or actually let me try again

quasi ridge
oblique hemlock
#

refused to connect

quasi ridge
#

which is to be expected, since I never "opened up" that port

#

close enough I think

oblique hemlock
#

Yup

quasi ridge
#

so either

  • shut down apache, and have flask listen on port 80, since we know that works already; or
  • tell vultr to open up port 5000
#

hint: if you do the first thing, you'll have to run your flask app as root, which sucks

oblique hemlock
#

All ports are opened

quasi ridge
#

then maybe flask isn't listening on port 5000

#

if it were, it'd say so when it started up

oblique hemlock
#

But still the same message

#

SO changing the port?

quasi ridge
#
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
#

do you have messages like those?

native tide
oblique hemlock
#

Yes!

quasi ridge
#

@native tide this channel is in use; type !f to find a free one

oblique hemlock
#

Exactly

quasi ridge
#

ok, what IP address do you see?

#

Is it 127.0.0.1 like mine?

oblique hemlock
#

Yup

quasi ridge
#

ok, fiddle app.run and tell it to listen on 0.0.0.0

oblique hemlock
#

And keep the port as 5000?

quasi ridge
#

127.0.0.1 isn't visible from the outside world

#

yeah keep the port at 5000

oblique hemlock
#
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat```
quasi ridge
#

looks good

#

I give you 60% chance of success

oblique hemlock
#

sent an invalid response.

native tide
#

im having trouble actually with getting other devices on my network it respond to 0.0.0.0 even though my local machine loads it

quasi ridge
#

well but you should at least see spew from flask acknowledging that it got a request, and responded ... ?

oblique hemlock
#

Yup!

quasi ridge
#

ok now you just haveto debug your app.

oblique hemlock
#

It's on debugging mode

#

Oh

#

My code you mean?

quasi ridge
#

yep

oblique hemlock
#

I see

native tide
#

you need to export FLASK_ENV=development if you are in development

quasi ridge
#

I can't think offhand what mistake you could have made that would cause your browser to complain about "invalid response" though

native tide
#

that isnt the solution to that tho

oblique hemlock
#

I might continue with google..

vagrant adder
#

@oblique hemlock mind sharing the code?

oblique hemlock
#

Thanks buddies!

#

@oblique hemlock mind sharing the code?
@vagrant adder Mhm

native tide
#

do you have a firewall? OR does your browser block ports maybe?

oblique hemlock
#

do you have a firewall? OR does your browser block ports maybe?
@native tide I don't know I will check

native tide
#

what is your os

oblique hemlock
#

Debian

native tide
#

sudo ufw status most likely

#

or without sudo just as root

vagrant adder
#
@app.route('/convert', methods=['POST'])
def convert():
    def long_time(url):
        #clear directories of previous songs
        clear_directories()
        #downlaod the audio from the link given
        yield download_from_youtube(url)
        #convert downloaded song in sample audio to 8d and save out
        wav_mono, wav_stereo, sampling_rate, tempo, beat_frame = song_features('./out/test.wav')
        yield "Loaded Song"
        wav = rotate_left_right(wav_mono, wav_stereo, tempo, sampling_rate)
        yield "Rotation"
        save_song('./out/in.wav', wav, sampling_rate)
        yield "Saved to Path"
        add_effects('./out/in.wav')
        yield "Added Reverb"
    return Response(long_time(request.values['url']))

yield doesn't work with flask, and you don't need to return Response()

#

yield means you are sending multiple requests to a client

oblique hemlock
#

I will edit that

native tide
#

is there a way to pass app.run() keywords that tell it the conditions of flask run

#

like the host, the port, etc

#

so i dont have to use command line options

quasi ridge
#

I think those yields are fine

#

they're in an internal function, not the function decorated with route

oblique hemlock
#

I commented them but the same

vagrant adder
#

what error

quasi ridge
#

the response will be built from a list of things

oblique hemlock
#

sent an invalid response.

native tide
#

...there is... reading answers to questions while asking them

oblique hemlock
#

156.194.47.19 - - [28/Mar/2020 18:00:30] code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x02\x00\x01\x00\x01รผ\x03\x03รŒรฒรฑ\x9aY\x06ร1รฆยต\x1bยบรŒรณ\x89\ยชยง2รฒS\x98\x052|รŸoร‹ยง\x84Oรˆ')
156.194.47.19 - - [28/Mar/2020 18:00:30] "รผรŒรฒรฑ๏ฟฝYร1รฆยตโ–’รŒรณ๏ฟฝ\ยชยง2รฒS๏ฟฝ2|รŸoร‹ยง๏ฟฝOรˆ รs๏ฟฝรฅ_๏ฟฝรฎยพ,๏ฟฝยดรฃ|K๏ฟฝtรŒรšu9รข{=ยพยณยงร’๏ฟฝ4ร–"รŠรŠร€+ร€/ร€,ร€0รŒยฉรŒยจร€ร€๏ฟฝ๏ฟฝ/5" HTTPStatus.BAD_REQUEST -
156.194.47.19 - - [28/Mar/2020 18:00:30] code 400, message Bad request version ('n\x00"zz\x13\x01\x13\x02\x13\x03ร€+ร€/ร€,ร€0รŒยฉรŒยจร€\x13ร€\x14\x00\x9c\x00\x9d\x00/\x005\x00')

quasi ridge
#

might be SSL

oblique hemlock
#

Um-

quasi ridge
#

is your browser going to https://your-site.com:5000?

oblique hemlock
#

I don't think so

quasi ridge
#

if so, make it http://

oblique hemlock
#

It's certificated tho

#

HTTPS

quasi ridge
#

dunno what that means

#

oh ok

#

stop that for now

vagrant adder
#

how are you accessing your flask site?

quasi ridge
#

serving https is a lot harder than http

brave mantle
#

you almost never want Flask to serve HTTPS

#

that's not Flask's job

#

you don't need it at all unless you're in production - in which case, you should be using nginx to service your users (nginx will handle https), plus a worker manager like gunicorn

quasi ridge
#

I think you could put nginx in front of flask safely. I think.

oblique hemlock
#

Any useful documents?

#

I would appreciate that

brave mantle
#

You can

#

But generally, Flask won't be able to handle more than one user at a time

#

Even though each transaction will probably take milliseconds

#

when you have a bunch of people accessing your site at once, you'll probably need workers to keep things fast

quasi ridge
#

that I can believe

#

I personally would put up with that, for the sake of simplicity; I'd switch to e.g. gunicorn only if it was clearly necessary

brave mantle
#

It's best to do the right thing first really

#

Then you can pretty much set it and forget it

oblique hemlock
#

I'm really confused now

brave mantle
#

This is one way to do it

native tide
#

it called the proxy pass.

brave mantle
#

nginx is known as a reverse proxy, yes

native tide
#

i learned to do that recently.

#

with django first but same idea

oblique hemlock
#

Thanks!

native tide
#

its a bit of a learning curve the first time i admit.

#

ther sysadmin that is

#

with the sysadmin stuff, when you get an error that is like, "Yo, the server said nah" which is like a 502 or something like that, you'll want to learn quickly to check logs. Things will work in development that wont work in production server. you have to get used to restarting gunicorn and editing various files in very specific ways. Small things like having a file in a directory that shouldnt be there will cause it bork and not tell you why (directly).

#

But in the logs is the answers usually

#

the web server config was not as hard for me as the database auth permission granting and denying.

#

but i got it eventually

#

Servers dont give obvious error messages. they hide them in files

#

how do you write a postgres url to a remote server's database that requires auth? I typically do psql -U postgres -h 192.168.123.456 -p 5432 -d the_database -W but for Flask I need something like postgresql://postgres@192.168.123.456:5432 ..but i also need to put a password and a database name to connect to somewhere in that url string right?

brave mantle
#

postgresql://user:password@host/database

native tide
#

wow. cool ty

#

i suppose that is best put into an environmentt variable then.

brave mantle
#

Generally, yeah

native tide
#

I uploaded my secret key to my first django test project's repo ๐Ÿ˜›

#

not that it mattered but thats how i learned

#
Note: Flask-Migrate makes use of Flasks new CLI tool. However, this article uses the interface provided by Flask-Script, which was used before by Flask-Migrate. In order to use it, you need to install it via:

Would you skip Flask-Script and just use whatever new CLI tool... I'm learning Alembic and migrations with Flask-Migrate.

native tide
#
class Result(db.Model):
    __tablename__ = 'results'

    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String())
    result_all = db.Column(JSON)
    result_no_stop_words = db.Column(JSON)

    def __init__(self, url, result_all, result_no_stop_words):
        self.url = url
        self.result_all = result_all
        self.result_no_stop_words = result_no_stop_words

    def __repr__(self):
        return '<id {}>'.format(self.id)

I see some people frequently skip the traditional __init__ method for setting attributes when they write Flask-SQLA models. I'm not sure why or why not. The properties are eventually accessible through q = Result.query.first() and then q.prop -- but is the difference that those values are from the DB and not attached to the instance at all? The syntax is otherwise the same for calling a prop from the db as from the instance. It doesnt cause any problems to do both does it?

#
class UserAccount(db.Model, UserMixin):
    """
    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)
    is_admin = db.Column(db.Boolean, default=False)

    player = db.relationship('PlayerProfile', uselist=False, back_populates="user")

    def __repr__(self):
        return f"User('{self.id}', '{self.email}')"

    def __init__(self, id, email, image_file, password, account_created, agree_over_18, is_admin, **kwargs):
        super(UserAccount, self).__init__(**kwargs)

        # Initialize Attributes
        self.id = id
        self.email = email
        self.image_file = image_file
        self.password = password
        self.account_created = account_created
        self.agree_over_18 = agree_over_18
        self.is_admin = is_admin

        # Create Row in DB When Created
        db.session.add(self)
        db.session.commit()

        # Apply a player profile to users on creation
        new_player = PlayerProfile(id=self.id)

        # Commit to DB
        db.session.add(new_player)
        db.session.commit()

this is my actual user model

#

Im not sure if the self.prop = prop lines are superfluous

native root
#

See here

native tide
#

ty

native root
#

I would argue, however, that the super call should set all of them by default so they're probably superflous

native tide
#

thants what it was thinking but not sure. I barely understand that super() thing to tbh. I know what it dose sort of but the syntax is confusing to me.

#

I put it there because it worked

#

it has variations that are more than just super().__init__()

#

I prefer not to have it in this code, it does seem extra.

queen bough
native tide
#

oh no, I get that part. I mean extra as in all the property saving that isnt necessary apparently. I get why you have to inherit the base classes traits. What confuses me is when the syntax looks like this

#
    def __init__(self, **kwargs):
        super(UserAccount, self).__init__(**kwargs)
#

what are those positional args?

queen bough
#

Print them and see!

#

Not sure what the purpose is in this context.

native tide
#

Oh, I know what keyargs do. Its the clarification of super(ClassName, self) that i dont get. Ive always seen it called with no arguments.

And to be honest, I dont know why Im using it here. I know why you typically want to inherit traits from a base class, but in this case, I literally just put it here because thats what Corey Shafer did when he wrote his user class and he didnt explain why. In fact he didnt add it at all until he discovered there was some error on a production server.

#

if i recall

#

I still dont even know what a Mixin is haha, i just use it.

#

Ill get to that soon

#

thanks to everyone for the the guidance btw

fallow warren
#

how do i start with django

#

ik some python

#

but im better with html and css

quasi ridge
#

read the django tutorial

jaunty quiver
#

How can one model polymorphism in django 3.0? I.E. I have a class Vehicle then I have the classes Plane, Car, Tank, Bike that all inherit the Vehicle class. Now I want to be able to select all Vehicles (aka getting the objects of all subclasses ( Plane, Car, Tank, Bike )) and set a subclassagnostic foreign key to Vehicles

#

Basically I either want django to recognize the Relationships OR I want to mirror all changes to tables of subclasses up to the Vehicle table.

nimble epoch
#

Can you guys suggest me a good django book

#

Or any sources

jaunty quiver
#

the official documentation.

#

The tutorial project shows you the basics.

nimble epoch
#

Thats near 2000 pages i think

#

Am i right?

jaunty quiver
#

I was referring to this one

#

pretty concise and teaches you the basics

#

It has <10 parts so it is not all that much to work through

nimble epoch
#

Yeah i used to read this

#

Which one you prefer django or flask

#

And of course have you studied any type of book to learn django?

jaunty quiver
#

django and I learned by making an exploration project in my freetime and then building on that.

nimble epoch
#

Oh nice

#

Thanks though man

native tide
#

So I wanna move this content box to that red line down anyone can help with css styling?

#

here is the css stuff for these content boxes

.content-section {
  background: #ffffff;
  padding: 40px;
  border: 1px solid #dddddd;
  border-radius: 3px;
  margin-bottom: 20px;
}```
#

@manic frost Can you help?

manic frost
#

Please don't ping random helpers.

#

Sorry, I'm not an expert in CSS

#

Have you tried searching how to do that?

native tide
#

idk how to define It on google

manic frost
#

replace margin-bottom with margin-top

#

and 20px is too little

native tide
#

but now I've too much gap between two posts

manic frost
#

Could you post the code via pastebin?

#

Or maybe jsfiddle or something like that

#

So that I can manipulate the css in real time.

native tide
#

just the css one?

manic frost
#

No, all the code

native tide
#

sure

nimble epoch
#

Try delete that margin bottom once

#

Might work

#

If the css file is the style of the posts itโ€™ll probably work

native tide
#

I did this and It worked css .content-section { background: #ffffff; padding: 35px; border: 1px solid #dddddd; border-radius: 3px; margin-top: 70px; margin-bottom: -90px; }

nimble epoch
#

๐Ÿ˜‚

native tide
#

v_gz I messes up with jsfiddle xD

nimble epoch
#

Ive never seen nicer than this

native tide
#

It was just an experiment xD

nimble epoch
#

๐Ÿ‘Œ๐Ÿฟ

native tide
#

@nimble epoch okay but I messed up with something else

nimble epoch
#

Thats ok

#

Just kidding

native tide
#

can you help?

nimble epoch
#

Yeh

#

Css?

native tide
#

yep

nimble epoch
#

not sure but TRY ME

native tide
#

wait 1s I think messed too much

nimble epoch
#

๐Ÿ˜†

native tide
#

Can I DM?

nimble epoch
#

Sorryy what

native tide
#

can I explain that in DM's?

nimble epoch
#

Explain

native tide
#

whatever xD Its gonna be too long

nimble epoch
#

Man you are a genius

native tide
#

lol why? what did I do?

nimble epoch
#

Nothin......

#

๐Ÿคช๐Ÿ˜

native tide
#

thing is ....

nimble epoch
#

I mean it Looks ok, no?

native tide
nimble epoch
#

Whata

#

I think you should check your html file

native tide
#

yep Its not a css thing

nimble epoch
#

Of course you yourself are a genius

#

๐Ÿ˜‰

native tide
#

Dude I'm a tech geek thats why + I'm a fast learner

nimble epoch
#

Wow

native tide
#

Its my first month of coding

nimble epoch
#

Oo

#

So good luck๐Ÿฅณ

#

I suggest you Codecademy

native tide
#

ty but can I ask you for help later?

nimble epoch
#

Of course

native tide
#

I did some codeacadmy stuff but not my thing

nimble epoch
#

There are a lot in here that can help

#

Rally?

#

No no

#

Codecademy

native tide
#

yep Its too boring

nimble epoch
#

I think theres another wabsite like codeacademy

native tide
#

I like only Scrimba cuz of their technology xD

nimble epoch
#

But thatโ€™s different

native tide
#

which one

nimble epoch
#

In codecademy You can learn by coding yaself

#

I think that was the best place

#

But Scrimba doesnโ€™t look bad

native tide
#

yep Scrimba is kinda interesting

nimble epoch
#

Yeah but i have never tried

native tide
#

okay I gtg

nimble epoch
#

Ok

rustic pebble
#

Yo, does anyone here use Quart?

nimble epoch
#

Never heard of it๐Ÿ˜

rustic pebble
#

It is basically an async version of flask

nimble epoch
#

Oh

#

I know flask but not sure about this one

rustic pebble
#

Nvm found it, there is an extension that allows you to patch things like res = make_response('') to res = await make_response('')

nimble epoch
#

Sorry๐Ÿ™ƒ Nope

rustic pebble
#

yea I figured it

native tide
native tide
#

I had a functional login page for my blog site and I wanted to redesign It and I did now Its not working can anyone help me to make It functional?

jaunty quiver
#

How can one model polymorphism in django 3.0? I.E. I have a class Vehicle then I have the classes Plane, Car, Tank, Bike that all inherit the Vehicle class. Now I want to be able to select all Vehicles (aka getting the objects of all subclasses ( Plane, Car, Tank, Bike )) and set a subclassagnostic foreign key to Vehicles
Basically I either want django to recognize the Relationships OR I want to mirror all changes to tables of subclasses up to the Vehicle table.

native tide
#

@native tide maybe use an image?

golden swift
#

Anyone know of a way I can create a type of flow map kinda drawing? similar to this.

#

It's not going to be static, it will grow, shrink, and change depending on whats stored in a DB.

#

I looked at jsplumb, but would like to stick with just something in python.

mighty herald
#

Hi guys i need some help. I set up SQLAlchemy and made a model class for users and one for SchedulePosts and I have a form that accepts one day of the week and the event. I need help setting up the view and schedule page template so that the users info gets posted to the same page as the form. Any input would be great, thanks!

mighty herald
#

*update i set up the view now im getting an error when trying to import the table but ill try and figure that out tomorrow

modest dirge
#

i made a repository for my website on github

#

and initilazied on my mac

#

and everything

#

and commited fil

#

but when i try to access the website through the github pages

#

it sayas 404 page not founf

native tide
#

I cant stop getting

  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 877, in apply_driver_hacks
    if sa_url.drivername.startswith('mysql'):
AttributeError: 'NoneType' object has no attribute 'drivername'

when I try to do anything with my database as postgres. le sigh. I think im too exhausted to even write up the problem tonight.

#

if I have environment variable exports inside of ~/.profile on Ubuntu based Linux, they should export right? For some reason I have to keep redoing that also every time i leave a shell.

#

I should probably call it a weekend. Im at the stage where my mind is mush now. I wish that never happened and I could just go on working for infinite time.

shadow hornet
#

that happens to even the best of us, a fresh mind the next day usually finds the problem

native tide
#

yeah, its best for me especially to be self aware about it so i can mitigate the possible damage to my work i sometimes do after exhaustion sets in if i dont face it for some reason..

#

So i try to do not do that ha

heady ore
#

How can I show the pdf content with FileResponse? I have the following code so far:

In views.py:
def pdf_view(path):
    path = str(path)
    print('PATH++++++++++++: ' + path)
    with open(path, 'rb') as pdf:
        # response = HttpResponse(pdf.read(), mimetype='application/pdf')
        # response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        response = FileResponse(pdf, content_type='application/pdf')
        return response
from paperPath.models import PaperPath
def get_path(request, pseudo_doi):
  pathInfo = PaperPath.objects.get(pseudo_doi = pseudo_doi)#.path
  pdf_content = pdf_view(pathInfo)
  return render(request, "paperInfo/detail.html", {'pdf_content': pdf_content})

and

In html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>PaperPath</title>
</head>
<body>
    {{ pdf_content }}
</body>
</html>

It's showing <django.http.response.FileResponse object at 0x7f9999267c88> now

native tide
solar hatch
#

i want to make a tic tac toe game

#

what should i use div,table

#

button

#

which is the easiest

native tide
#

hi, I made a blog site in this site If I click on a posts author name It refers me to users other posts, I know how It works but the question is how do I refer it to authors profile I already have users profile template, what should I do?

native tide
#

Are you using Flask or Django?

#

Django

#

@native tide

#

So, inside of an href you will use {% url 'blog-home' %} 'blog-home' is an example of a name for view attached to the urlconf like this

urlpatterns = [
    path('', PostListView.as_view(), name='blog-home'),
    path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/edit/', PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
    path('about/', views.about, name='blog-about'),
]

#

<a href="{% url 'password_reset' %}">Forgot Passoword?</a>

#

I wanna refer It to the authors profile not the users own profile

nimble epoch
#

@native tide also you can create a url that redirects it like redircet(โ€œprofileโ€, id=user.id) in the main page that you want to click on the username

native tide
#

in url conf you make a url configuration that takes a variable

#

for example look at this one

#

path('user/profile/<str:username>/', ...etc

#

and then just set up a view that takes the argument and redirects there

#

I might not be the best at explaining it because i dont use django very much

#

So I need a separate template for authors profile?

nimble epoch
#

Yeah

native tide
#

Yes, not for each profile, but in the template youll use jinja to display content based on which user it is

#

Is jinja a separate library of django?

#

oh well actually, its just similar to DTE.

#

Theyre slightly slightly different

#

Django originally used jinja i think

#

and then made it thier own a little

#

I guess I already have It in Pycharm

#

I have an error in the web browser that is blowing my mind. PyCharm says it finds no error

#

AttributeError
AttributeError: 'str' object has no attribute 'c'

#

And I know that sounds like a typo... but I cant find it

#

Its simply a spell mistake

#


        else:

            table = cls.__table__

            if declared_columns:

                for c in declared_columns:

                    if not table.c.contains_column(c):

                        raise exc.ArgumentError(

                            "Can't add additional column %r when "

                            "specifying __table__" % c.key

                        )

        self.local_table = table`

its referring to this as c I think

#

sorry for that ugly code

#

its from the debug browser

#

Its some error on my models file because I barely understand what im doing

#

SQLA is so much more complicated than Django ORM

#

!paste

lavish prismBOT
#

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.

native tide
#

Its blowing my mind too ๐Ÿ˜‚ cuz I'm not too much familiar with all things yet

#

its all good, web frameworks are.. a lot.

#

im new also

#

totally stumped

#

i made too many changes to the models file without checking what it would do

#

omg haha

#

an extra set of eyes is a good thing

#

ty

#

OH FUCK is it what you were looking for?

#

yeah thats definitel it haha

#

i was just looking for 'c'

#

that was weird

#

Dude I'm doing coding for only one month but now I guess I'm getting it

#

Good feeling when you can help someone, i know how it is.

#

yep

#

I will say, Django is definitely a steep curve for only one month in but if thats what you want you can do it

#

Its my first project but If you wanna see I can show you Its fully functional now I'm just improving it

#

damn maybe thats not it... Im going to have pour over this code. I might be too sleepy to do well rn ha Ive been awake all night...

#

Sure

#

same

#

well I'm gonna look again If I can find anything

#

but are you still getting the same issue?

#

I mean the same error?

#

yeah

Traceback (most recent call last):
  File "/home/virufac/Projects/shell_hacker_game/shellmancer/__init__.py", line 33, in <module>
    from shellmancer import routes
  File "/home/virufac/Projects/shell_hacker_game/shellmancer/routes.py", line 3, in <module>
    from shellmancer.forms import RegisterForm, LoginForm
  File "/home/virufac/Projects/shell_hacker_game/shellmancer/forms.py", line 6, in <module>
    from shellmancer.models import UserAccount
  File "/home/virufac/Projects/shell_hacker_game/shellmancer/models.py", line 119, in <module>
    class CharacterSheet(db.Model):
  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/flask_sqlalchemy/model.py", line 67, in __init__
    super(NameMetaMixin, cls).__init__(name, bases, d)
  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/flask_sqlalchemy/model.py", line 121, in __init__
    super(BindMetaMixin, cls).__init__(name, bases, d)
  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/api.py", line 75, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 131, in _as_declarative
    _MapperConfig.setup_mapping(cls, classname, dict_)
  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 160, in setup_mapping
    cfg_cls(cls_, classname, dict_)
  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 190, in __init__
    self._setup_table()
  File "/home/virufac/Projects/shell_hacker_game/venv/lib/python3.8/site-packages/sqlalchemy/ext/declarative/base.py", line 544, in _setup_table
    if not table.c.contains_column(c):
AttributeError: 'str' object has no attribute 'c'
#

i think it has something to with me refactoring stuff

#

This is all stuff im trying to figure out so i should have done so much to the code without testing it

#

ill find it

#

Read these two lines carefully

if not table.c.contains_column(c):
AttributeError: 'str' object has no attribute 'c'
``` @native tide
#

maybe i just need to stop all the data and restart...

#

i thought i did that

#

i should just take a break from this, im starting to forget silly things

#

i hope thats it

#

haha well i cant even get into the shell to drop it

#

yeah that is not my code, that is a lib so it measn...

#

something i have done has broke stuff

#

and its not obvious what except that maybe dropping all the data will work

#

that cant be it because... i put in an entirely different database. same error. It has to do with my relational mapping being horrificly bad.

#

that is what it is lol

#

SQLA is hard

#

to be fair my database is a little overly complex for a first database but whatever

#

Dude I tried but yet Its not my thing xD

#

its all good i think im too tired to deal with it now, It involves going back over everything i added and removing it or waiting for database expert to correct me. ha

#

thanks tho

#

can i ask a question about flask here?

#

i'm trying to make a registration form but i'm failing miserably ๐Ÿ˜ฆ

#

!ask

lavish prismBOT
#

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.

native tide
#

so

#

feel free

#

class UserRegistryForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Register')
#

like so

#

right?

#

this is mine

#
class RegisterForm(FlaskForm):
    email = StringField(email_name,
                        validators=[DataRequired(),
                                    Length(min=4, max=32),
                                    Email()],
                        render_kw={"placeholder": email_name})

    password = PasswordField(password_name,
                             validators=[DataRequired(),
                                         Length(min=8)],
                             render_kw={"placeholder": password_name})

    password_confirm = PasswordField(password_confirm_name,
                                     validators=[DataRequired(),
                                                 EqualTo('password')],
                                     render_kw={"placeholder": password_confirm_name})
    submit = SubmitField('Sign Up')
#

wait

#

i just need to get a really basic one going first

#

right, so what isnt working about it?

#
@app.route('/register', methods=['GET', 'POST'])
def register():
    registerForm = RegisterForm()
    if registerForm.validate_on_submit():
        flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
        return redirect('/index')
        

    return render_template('register.html', registerForm=registerForm)```
#

then i define this in routes

#

and then i have a register.html file

#
{% extends "index.html" %}

{% block body %}
    <body>
    <h1>Create an account</h1>
    <form action="" method="post" novalidate>
        {{ registerForm.hidden_tag() }}
        <p>
            {{ registerForm.name.label }}<br>
            {{ registerForm.name(size=32) }}
        </p>
        <p>
            {{ registerForm.email.label }}<br>
            {{ registerForm.email(size=32) }}
        </p>
        <p>
            {{ registerForm.password.label }}<br>
            {{ registerForm.password(size=32) }}
        </p>
        <p>{{ registerForm.submit() }}</p>
    </form>
    </body>
{% endblock %}```
#

Unrelated but you should use f-strings instead of .format when you can. im looking and comparing it to mine hold on

#

Internal Server Error

#

mm

#

ok thanks!!

#

does that happen when?

#

does it happen as soon as you load site or when you click submit to register?

#

I'm not seeing what you're doing wrong other than little things tbh but im moments away from passing out.

#

good luck

native tide
#

welp, with my problem

#

the only thing that fixes it is removing this of all things

class CharacterSheet(db.Model):
    """
    A character sheet is issued by a GM to a campaign and as a result to every player
    who rolls a character in that campaign. The character sheet is a blank template for a character.
    """
    __table__ = 'character_sheets'
    character_id = db.Column(db.Integer, primary_key=True)
    player_id = db.Column(db.Integer, db.ForeignKey('player.id'), nullable=False)

I have no idea why but i know that im done for now. wayyy too tired.

#

"fixes it"

#

the database is still trash but it loads again

rustic pebble
#

Hey, so I am facing an error concerning an OAuth login system. Basically I am trying to add discord as primary auth means for my website

#

this is my code. I am getting invalid OAuth2 redirect_uri

from flask import Flask, redirect, url_for, render_template, session
from requests_oauthlib import OAuth2Session
import oauthlib
import os

app = Flask(__name__)
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['FLASK_DEBUG'] = '1'
client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv('CLIENT_SECRET')
app.config.update({'OAUTH1_PROVIDER_ENFORCE_SSL': False})

authorization_base_url = "https://discordapp.com/api/oauth2/authorize"
token_url = 'https://discordapp.com/api/oauth2/token'

scopes = ['identify', 'connections']


@app.route('/')
def home():
    return render_template('index.html')

@app.route('/user')
def user_settings():
    return render_template('user-settings.html')


@app.route('/login')
def login():
    oauth = make_oauth()
    authorization_url, state = oauth.authorization_url(authorization_base_url)
    session['oauth_state'] = state
    return redirect(authorization_url)

@app.route('/callback')
def callback():
    oauth = make_oauth()
    oauth.state = session['oauth_state']
    try:
        token = oauth.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url)
    except oauthlib.oauth2.rfc6749.errors.InvalidClientIdError:
        return redirect('/')


#HELPER FUNCTIONS
def make_oauth():
    return OAuth2Session(client_id, scope=scopes, redirect_uri=url_for('callback', _external=True))


if __name__ == "__main__":
    app.secret_key = os.urandom(24)
    app.run(host='localhost', debug=True)
valid cypress
#

How to use async views in Django dev?

woeful swallow
#

Is anyone available to help with a question related to Flask and SQLAlchemy?

nimble epoch
#

Maybe i can

native tide
#

@nimble epoch

#

i have a question about flask

nimble epoch
#

Maybe i can help

native tide
#

do you know how to do the flask-wtf registration page?

nimble epoch
#

Ye

native tide
#

omg

#

amazing

#

i just want to do a really basic one

#

like not linked to any database or anything

#

so in forms i have this py class UserRegistryForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Register')

nimble epoch
#

Ohh seems easy

native tide
#

that look ok?

#

then in routes i have this ```py
@app.route('/register', methods=['GET', 'POST'])
def register():
registerForm = RegisterForm()
if registerForm.validate_on_submit():
flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
return redirect('/index')

return render_template('register.html', registerForm=registerForm)```
nimble epoch
#

Ye

native tide
#

(nts about that ^)

#

and then i have this html sheet

#

called register.html

#
{% extends "index.html" %}

{% block body %}
    <body>
    <h1>Create an account</h1>
    <form action="" method="post" novalidate>
        {{ registerForm.hidden_tag() }}
        <p>
            {{ registerForm.name.label }}<br>
            {{ registerForm.name(size=32) }}
        </p>
        <p>
            {{ registerForm.email.label }}<br>
            {{ registerForm.email(size=32) }}
        </p>
        <p>
            {{ registerForm.password.label }}<br>
            {{ registerForm.password(size=32) }}
        </p>
        <p>{{ registerForm.submit() }}</p>
    </form>
    </body>
{% endblock %}```
nimble epoch
#

Your form name in the route is not same as your form name

native tide
#

:0

nimble epoch
#

๐Ÿ˜‰

native tide
#

shitt

nimble epoch
#

Ohhh shiiit

native tide
#

ok 1 sec

#

@nimble epoch

#

i still get internal server error

#

when i click on the button that should lead me there

nimble epoch
#

What?

native tide
#

i click on get started

#

i get this

nimble epoch
#

Wait a sec

native tide
#

oki

nimble epoch
#

First i think you didnt add remember me field to ya form

native tide
#

oh

nimble epoch
#

Did you add?

native tide
#

yeh

#

do i need to restart the server

nimble epoch
#

If debugger is not on

native tide
#

yeh stil internal error

nimble epoch
#

Can i see the form

native tide
#

sure

#
class RegisterForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Register') ```
nimble epoch
#

Can i see ya whole files to make sure everything is alright?

native tide
#

@nimble epoch

#
NameError: name 'RegisterForm' is not defined
#

thats my error

nimble epoch
#

Oh

#

So as you know you should check your variables

native tide
#

yeh

#
app.route('/register', methods=['GET', 'POST'])
def register():
    registerForm = RegisterForm()
    if registerForm.validate_on_submit():
        flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
        return redirect('/index')
        

    return render_template('register.html', registerForm=registerForm)
#

looks fine?

#

oh fuk

#

i didnt import it

nimble epoch
#

Yeah of course you did change the form name, Didnโ€™t you?

native tide
#

yep

#

i just sent it to you

nimble epoch
#

If thats the same everything is ok

#

But not the form

native tide
#

oh

#

the html?

nimble epoch
#

No the flask form

native tide
#
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')

class RegisterForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Register')
    ```
#

heres the entire form file

nimble epoch
#

And of course you did import the forms to your routes file

native tide
#
from app import app
from flask import render_template, flash, redirect
from app.forms import LoginForm, RegisterForm

@app.route("/")
@app.route("/landing")
def landing():
    return render_template("landing.html")

@app.route("/index")
def index():
    site_title = "Site Title"
    welcome_string = ""
    return render_template("index.html", welcome_string=welcome_string, site_title=site_title)

@app.route("/about")
def about():
    name = "Nobody"
    return render_template("about.html", name=name)

@app.route("/login", methods = ["GET", "POST"])
def login():
    loginForm = LoginForm()
    if loginForm.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(loginForm.username.data, loginForm.remember_me.data))
        return redirect('/index')
    return render_template('login.html', title='Sign In', loginForm=loginForm)

@app.route('/register', methods=['GET', 'POST'])
def register():
    registerForm = RegisterForm()
    if registerForm.validate_on_submit():
        flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
        return redirect('/login')
        

    return render_template('register.html', title='Register' registerForm=registerForm)

#

yep

#

good news is

#

i dont get the internal server error anymore

nimble epoch
#

๐Ÿฅณ

native tide
#

but the bad news is, it redirects me back to the start page

#

it doesn't load a form

nimble epoch
#

What?

native tide
#

like i click register

#

i doesn't change to a register page

#

well the URL changes but the page hasn't changed

#
          <li><button class="plain-button" onclick="window.location.href='/register';">Get Started</button>
#

thats the button

nimble epoch
#

You mean when you click on the register it dosnt bring you to the register page?

native tide
#

yeh

nimble epoch
#

Give it a link

#

I always use <a> tag and give it the class to make it like a button

#

Did it work?

native tide
#

it works fine for the login button using this method

nimble epoch
#

whats the error for register

native tide
#

no error

#

just a get request

nimble epoch
#

Ob

native tide
#

it must be my route

#

idk

nimble epoch
#

Im not sure about this one because i dont have your files

native tide
#

i can send them if you want

nimble epoch
#

But use request.method = โ€œGETโ€

#

Maybe works

native tide
#

where?

nimble epoch
#

Use it inside your register route

#

Exactly after def register()

native tide
#
def register() request.method="GET":
    registerForm = RegisterForm()
    if registerForm.validate_on_submit():
        flash('Registration requested for user {}, remember_me={}'.format(registerForm.username.data, registerForm.remember_me.data))
        return redirect('/login')
        

    return render_template('register.html', title='Register' registerForm=registerForm)````
#

likes o?

nimble epoch
#

Oh put : after your function

#

And delete it after โ€œGETโ€

native tide
#

IndentationError: unexpected indent

nimble epoch
#

Ok that didnt work

native tide
#

i'll send you my files

#

if u want

nimble epoch
#

Of course

thick cove
#

Hey, what django model type does postgresqls json equal?
Nevermind! django.contrib.postgres.fields.JSONField

native tide
#

If anyone knows or can give me a hand

rustic pebble
#

Has anybody ever setup AWS RDS with flask_sqlalchemy?

haughty haven
#

I've used sqlalchemy with AWS RDS aurora Postgres before

#

It behaves no differently from a normal postgres database

#

You just have to make sure you can access it from the VPC it's in

#

If you're trying to get to it from your local machine you can set up an ec2 instance in that VPC to be an SSH tunnel proxy for your local running code

native tide
#

What are blueprints? (flask adjacent)

#

simple explanation is fine. just curious

earnest oak
#

how hard would it be to make your own vpn?

quasi ridge
#

for me? impossible

#

for someone who knew something about networking? dunno

tired root
#

If you know basic routing, not very difficult

#

You can try it out with your computer and a phone

#

dont even need an app

#

However, what gets sold as VPN these days, isn't really the definition of VPN

quasi ridge
#

to me, VPN means "encrypted"

tired root
#

VPN means a private connection between two trustworthy networks over an untrustworthy medium

#

So, connecting to a VPN server to feed internet into the other side, which is untrustworthy, isn't really a vpn

#

using HTTPS is enough encryption

native tide
#

yeah, I no longer really care for commercial VPN anymore.
I dont particularly like my ISP (or any ISP), but I'm not sure that modern VPN sold by proprietary businesses is really in the spirit of privacy exactly.
It has a use case... but its not a cure all for ownership of your home and what goes on it or anything.
If its contrary to profit, they will not uphold privacy, not unless they take it a little more seriously than they seem to.
They are essentially just middle men holding on to this data and I'm not seeing anything that verifies no logging and frankly not feeding whatever to machines to process for further business ha.

But yeah, I had PIA about a year ago and they have been bought out by scumware.

I like this https://www.vpngate.net/en/ because it's run by an educational instittuion at primarily a Japanese university in attempts to spread Internet and info to places where it is being supressed.

They are good for temporary use cases if you need a proxy IP for some reason. But overall, its not a perfect privacy solution at all.

tired root
#

You are just giving your browsing behaviour to the vpn provider instead of your ISP

native tide
#

exactly

tired root
#

at least your ISP is in the same country and you can sue them should violations occur

native tide
#

and if they are just another corporation becoming just as big and evil then same thing

tired root
#

I am using end-to-site VPN for free Wifi

#

that is for example a good use

#

I connect to my router at home, so at least people in the same wifi can't spy on me

native tide
#

Thats true you def have to pay attention to where you geta VPN service from

tired root
#

and due to my work, I see what kind of traffic comes out of some vpn providers

#

can't go into specifics, but it's awful

native tide
#

Its hard to use those commercial VPNs because they are so constantly getting shut down. People act like you are the shadiest around for using it. I dont care for that sentiment either. But yeah.

#

Like services are regularly fighting them is what i mean

#

you have to jump ips frequently

#

to keep service

tired root
#

VPN's use data centers, not ISPs

native tide
#

I like the idea in theory. But after paying for various services and watching their behaviour and looking at the reality of it, it is not something i would rely on if there was something truly grave that not be in data or something. If. There is a use case for it but... its not "got VPN am protected" kind of thing.

#

I typically will configure one of those proxies and use if i need to to get through some service that is being dildoish and then ill drop out of it after

#

tbh i dont typically need to do that

#

but it happens

tired root
#

There is also the issue of IPV6 and DNS leaking, which many do

#

Then, websockets

native tide
#

yeah. I was paranoid about that. I did some tests that seemed like it was not when I was really into it.

#

I actually know almost nothing about ipv6

#

I can identify them from looking at them

#

but thats it

tired root
#

It's really the same as IPV4, for the grand scheme of it

#

Just more numbers

native tide
#

do they do local subnet ranges in ipv6?

tired root
#

I mean, yes, lot's of differences in the nitty gritty details, but overall, not something the usual guy worries about

#

Yes

#

fc00::/7 to fdff::/7

native tide
#

I see 2600 in them somewhat frequently. My friends from hackers.town seem to reference 2600 often.

#

they are just white hats btw

vagrant adder
#

@native tide so blueprints are a way to organize your routes

#

imagine blueprint to be a small instance of app which can make routes and such

#

and they are registered back into app

rustic pebble
#

Is there a way I can hide scrollbars inside some elements?

#

this is not the corner of the page

shadow rock
#

how do you use flask-sqlalchemy inside a celery task

rustic pebble
#

@shadow rock you can't, sqlalchemy is blocking and is sync

shadow rock
#

you can

#

i'm trying to access the db and do some changes while inside a task

#

apprantely you have to pass in flask configs

#

@rustic pebble you can use css

#

overflow:hidden

rustic pebble
#

I found it anyways

#

๐Ÿ˜›

native tide
#

https://paste.pythondiscord.com/iguyepipuj.py
returns
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got '='
it's driving me nuts because I can't find anything online. I know it has something to do with my {{ }} brackets but idk

native root
#

This is wrong:

#
{{ url_for('static'), filename='main.css'  }}
#

You're closing the parens early

#

@native tide

native tide
#

??

#

so should I do it after the quote?

native root
#

flask's syntax mirrors pythons

#

if you're calling the url_for function with those two parameters, what's wrong with your )?

native tide
#

I got it

#
<link rel="stylesheet" type="text/css" href={{ " url_for('static'), filename='main1.css'" }}>
#

i'm dumb. thanks

native tide
#

nvm i'm still not getting this correct/

#

main.css doesn't seem to be working. my editor shows my code in green on the same line

#

nvm got it

golden swift
#

Asked a few days ago but I think it was late so just going to repost one more time then i'll shut up.. I'm tryin to almost like a connect the dots on one of my pages but the amount of dots that show will be dependent on a value im pulling from a DB. Something similar to this screenshot could be either like the top or bottom..

#

I looked at something like Vega, but seems to complex for my needs..

rustic pebble
#

@native tide that is still not how it should work judging by ur screenshot

native tide
#

I know. i fixed it

pallid loom
#

which front-end framework to use with django?

#

for a great project

white ermine
#

@pallid loom you can use any framework depending on your use case. I personally like Vue, but in most cases django's template system is sufficient for me.

pallid loom
#

@white ermine tks

native tide
#

anyone here familiar with flask?

#

i've setup a login page using flask-wtf

#

how do i link the sign in button so that it redirects to a new page?

nimble epoch
#

First you should use flask login extension

#

And you can use redirect() to for redirecting to other pages

tired root
#

@native tide The form action defines the target of the form

#

Just use url_for to direct the form action to the route handling the input

native tide
#

@nimble epoch so i should cancel the flask-wtf i've done?

tired root
#
<form method="POST" action="{% url_for("function_in_python_that_handles_the_route") %}">
{# wtf form vars #}
</form>```
native tide
#

thanks! @tired root

nimble epoch
#

They are different

#

Flask wtf is your form

#

Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out

zealous igloo
#

for django rest serializers, woudl it maek sense to have two serializers iwth teh same model if you want sometimes for certain feilds to be required and other times not

feral minnow
#

Guys im trying to make a mp3 downloader website but when I put the download link <a href="{{filePath}}" download>download</a>

#

then I just click on the download link but nothing happen

#

and im using flask

turbid glen
#

#t1 { transform: translate(100px) scale(2,1); background:red; } #t2 { transform: scale(2,1) translate(100px); background:green; }

#

why the result for these 2 arent same?

#

both of them are width 50px height 50px, margin left 0

tired root
#

Are their parents different?

#

@turbid glen

turbid glen
#

yes, its different, 2 <div>

tired root
#

@turbid glen Have you checked if the divs inherit anything from the parents that may cause it?

#

Chrome or Firefox debugger is helpful there

feral minnow
#

Guys Im trying to render my css file into the html file but its not working (im using flask) anyone can tell me why I put the right path and put on static folder but its not working?!!

nimble epoch
#

Guys im stuck between django and flask

#

Which one is better and more common for a web application

#

?

feral minnow
#

hmm Im just a beginner with these stuff but I always hear that flask is easier to start than django so I think you have to start with flask then go to django its more professional

rigid laurel
#

Django is very good if what you're doing fits the model it was designed for. E.g storing, querying, and presenting data to the user

#

Flask is better if you want to do extra things on top, or customise the way you do things

#

I think if your end goal is a web app with a database, then Django is probably easier to get started with - you don't have near as many annoying set up barriers

rich bobcat
#

Hey, I see here keywords like Django and Flask. Possibly you could help me.
I have a question connected with dbs and Django orm.

from django.db import models
class Family(models.Model):
  pass
class Parent(models.Model):
  name = models.TextField()
  family = models.ForeignKey(Family, related_name="members")
class Boy(Parent):
  favourite_car = models.CharField(max_length=10)
class Girl(Parent):
  favourite_doll = models.CharField(max_length=10)

actually I need serializer to present Family and it's members

class FamilySerializer(serializers.ModelSerializer):
   members = ... ??

I've got an idea how to serialize separetly.. to make members = serializers.SerializerMethodField() but I cannot find out how to separate Boy from Girl
Actually as a result I want to receive something like:

# family object
{
  members: [
    { # a boy
      name: "Karl",
      favourite_car: "Dodge"
    },
    { # a girl
      name: "Ann",
      favourite_doll: "Barbie"
    }
  ]
}
nimble epoch
#

Yeeeah ok thanks guys

rich bobcat
#

Hey, I see here keywords like Django and Flask. Possibly you could help me.
I have a question connected with dbs and Django orm.

from django.db import models
class Family(models.Model):
  pass
class Parent(models.Model):
  name = models.TextField()
  family = models.ForeignKey(Family, related_name="members")
class Boy(Parent):
  favourite_car = models.CharField(max_length=10)
class Girl(Parent):
  favourite_doll = models.CharField(max_length=10)

actually I need serializer to present Family and it's members

class FamilySerializer(serializers.ModelSerializer):
   members = ... ??

I've got an idea how to serialize separetly.. to make members = serializers.SerializerMethodField() but I cannot find out how to separate Boy from Girl
Actually as a result I want to receive something like:

# family object
{
  members: [
    { # a boy
      name: "Karl",
      favourite_car: "Dodge"
    },
    { # a girl
      name: "Ann",
      favourite_doll: "Barbie"
    }
  ]
}

@rich bobcat Is there any meta fields for example (Family()).mebmers.find_one().meta.class_name == "Boy" ?

tired root
#

@nimble epoch These kind of snarky comments won't get you anywhere

#

People here are often just idling while doing other stuff

#

But anyway, it is a matter of taste and usage. I like flask because it is simple and allows me to do things my way, while Django is more strict in my opinion.

nimble epoch
#

I have worked with django and flask already

#

But not sure about popularity and of course about salaries im not sure

#

And django is not that hard

#

But i myself think flask in more fun

tired root
#

What does popularity have to do with it?

nimble epoch
#

You wat im saying

#

Popularity i mean jobs that you can find

tired root
#

I've also never said Django is hard

rigid laurel
#

Salary depends on where you're based. Look at local job postings

nimble epoch
#

Djangoโ€™s is more

rigid laurel
#

If you're just looking to build a portfolio, it doesn't really matter which of the two you use

nimble epoch
#

Yeah ya right too

#

How about communities

#

Which One has more community

rigid laurel
#

Django probably has a bigger community - but thats because it does more things. With Flask you need to branch out and use other libraries, you don't need to near as much with Django

#

although again, I'm not sure why it matters

nimble epoch
#

You yaslef which one ya prefer

rigid laurel
#

I already explained my approach to two

nimble epoch
#

Thatโ€™s alright

#

But which one yourself use

rigid laurel
#
Flask is better if you want to do extra things on top, or customise the way you do things```
#

I use both, the right tool for the job

nimble epoch
#

Ok thanks

rich bobcat
#

Hey I would like to ask some question. Is there way to separate fields in DRF serializes to fields for serialization and deserialization.
It's like:

class MySerializer(serializers.ModelSerializers):
  class Meta:
    model = MyModel
    fields = ("name", "last_name",)
    deserialize_fields = ("id", "name" "age", "last_name",)

to make asymmetric parsing?
I have an assumption, but I am not sure. Are fields connected to serialization, but in the opposite way it will parse everything?

feral minnow
#

Hey guys I have this flask code ```
@app.route("/link-mp31")
def converter(file,fileName,folderPath):#File converter (from mp4 to mp3)

filePath=path(file)#Get the file path

video=VideoFileClip(file)#Create the object
    
video.audio.write_audiofile(f'{folderPath}\\{fileName}.mp3')#Convert the file

video.close()
return render_template("download.html", filePath=filePath)```
#

How I can give its arguments a value from another function/app

rich bobcat
#

It sounds weird. Just call it as proxy:

your_vars = [file, fileName, folderPath]
@app.route()
def route_handler():
  return converter(*you_vars)
def converter(*args):

or create decorator, or functools partial

frosty mauve
#

Here.

queen bough
#

@frosty mauve Can't you do this - once the input has been got from the user, create a model with a path attribute?

#

BTW, do you have the link I sent?

frosty mauve
#

Well that is what I am getting confused with. I download an image and want to set the ImageField to the image but I think it has to do with like upload_to putting it in a weird place. I can manually override it with a static url and it will work but when I use save() on it creates a url that doesn't link properly

queen bough
#

@frosty mauve As you can see, you can choose the folder (in the example's case it is cars).

frosty mauve
#

I also was reading about how maybe just create a separate model named Images and link it to the car object, not sure if that is standard practice though

#

is cars in static or media though?

queen bough
#

media I think. What was your problem again (sorry, I've forgotten)

feral minnow
#

guys how i can let the user download a file from a website using flask?

frosty mauve
#

I want to create a new obj with a photo stored locally so I don't have to manually click upload image in a GUI over and over

queen bough
#

Oh right, automatically add all the images as models?

frosty mauve
#

essentially create a bunch of new cars with their respective photos

queen bough
#

That's all?

frosty mauve
#

Yes

#

newcar = Car(name='Stupid Car', photo='') and it actually work lol

#

It works fine if I use admin

queen bough
#

So what's the problem with that?

frosty mauve
#

Let me give you exact problem brb

queen bough
#

Sure.

frosty mauve
#

ok so if I set the image field = to the path of the image

#

and then save, then call image.url it gives media/originalpathtoimage

#

media in the front?

queen bough
#

I see.

#

I think you can set absolute path?

#

One sec.

#

Can you send the code that you are using?

#

To create the model @frosty mauve .

frosty mauve
#

class Book(models.Model): image = models.ImageField(upload_to='images/', default='example.jpg')

queen bough
#

Hmm, I see your problem.

#

Can't you have the images in the media folder?

#

It's been a while since I've used media, but it is fine once you set it up correctly.

frosty mauve
#

I could try that, I was under the impression through reading online that media is reserved for user uploaded content

queen bough
#

So is the issue creating models or opening the files from Django?

frosty mauve
#

Create an object from the model with the image field populated and working

queen bough
#

MEDIA_ROOT this is the absolute path to the folder that will hold our user uploads. For example MEDIA_ROOT = "/User/Timmy/Sites/Pho/root/media/".

#

Is that set correctly for you?

frosty mauve
#

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

queen bough
#

OK, and you have all the files already in media?

frosty mauve
#

I do

#

I had them in static but now I have them in static and media

#

oh

#

Okay, so it works when I use media to upload from

queen bough
#

Yeah?

frosty mauve
#

I used admin though

queen bough
#

I see. Now it should be easy to replicate from shell

#

Do you know how to create models from the shell?

frosty mauve
#

Here is what I will do

#

`from books.models import Book

newbook = Book()
newbook.image = 'pathtoimage'
newbook.save()`

queen bough
#

Yup, and you can use a for-loop

#

To load all the images in media/

#

Know how to do that?