#web-development

2 messages · Page 36 of 1

drowsy stratus
#

hello :>

sly canyon
#

@drowsy stratus Can you share your code?

drowsy stratus
#

ok

#

should i show my template, url and view page

#

or anything more

sly canyon
#

You should share your ajax call

#

I'm not used to Django, but if you can share code within your your python application that receives the ajax call, it'd be nice too

drowsy stratus
#

im really dumb how do i attach a file in discord

lavish prismBOT
#

Hey @drowsy stratus!

It looks like you tried to attach a file type that we do not allow. We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv.

Feel free to ask in #community-meta if you think this is a mistake.

sly canyon
#

You should just paste the code itself, not the file

#

!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.

sly canyon
#

@drowsy stratus try using the character below 3 times between the first and lass line of your code, also add the language of the code on the first line after the triple

#

`

#

` (grave accent) not " or '

#

and the language name ( javascript ) should come just after the triple `

drowsy stratus
#

thx :>

sly canyon
#

Delete your code andj ust edit it, not to flood the channel :)

#

Try inserting "javascript" in the first line, without any whitespaces between the triple grave accent and the name of the language

drowsy stratus
#

wait is that incorrect too

#

        $(window).bind("mousedown", function() {

            $.ajax(
            {
       
                type:"POST",
                url: '{% url 'clickPage' %}',
                dataType: 'json',
                data:  
                {
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                },
        
                success: function(data) {
            
                    console.log("Success.");
         
                }
            
            });

        });```
sly canyon
#

cool, much better

#

Here's an implementation of an request on my current working personal project, it may help you on that:

#
    $(function() {
      $('#mark_all_as_read').bind('click', function() {
        // reaload notifications menu
        $.post("/notifications/mark_all_as_read").done(function(data) {
            $("#notifications-viewer").load(" #notifications-viewer");
            $("#pending-notifications-counter").load(" #pending-notifications-counter");
        });
       return false;
      });
    });
#

Your success function is only printing Sucess in the console log, it doesn't seem to be interacting with your application

drowsy stratus
#

how do i get it to run the correct view from there

sly canyon
#

what's the route that should receive that post request?

drowsy stratus
#

I am really new to django, or any web developement, so I thought I gave it a url, the url module would see it and direct it to the correct view

#

is that what the route is?

#

or do I not have a correct understanding of django

sly canyon
#

I really don't know anything about Django 😅

drowsy stratus
#

What is exactly happening in your code

sly canyon
#

But I know that: You have to explicitly tell what's the endpoint that will receive that post request

#

My code only triggers a function in my App that marks all notifications from users as read, so it doesn't really need arguments.

#

I just need to point to the route

#

As soon it triggers that route, all notification as marked as read

drowsy stratus
#

which function triggers the code

sly canyon
#

This is my routes.py route that receives that POST request

@app.route('/notifications/mark_all_as_read', methods=['POST'])
@login_required
def mark_all_as_read():
    for notification in current_user.notifications:
        notification.pending = False
    db.session.commit()
    return(render_template('index.html'))
#

The javascript function I posted above,
It's bound to an event listener on the element which id = #mark_all_as_read, as soon the user clicks on it it triggers the post request

drowsy stratus
#

wait so does that post request run the method

sly canyon
#

Yes, exactly

drowsy stratus
#

wait, so you need to give the location of the method, and then that post method would run it?shocked

sly canyon
#

Yup!

drowsy stratus
#

Thank you 😀

#

and thx for telling me how to insert code into discord

sly canyon
#

try using $.postthough

#

See if that works out for you

drowsy stratus
#

ok

sly canyon
#

@drowsy stratus Apparently I'm not completely right. Your code should be working from what I'm currently reading

drowsy stratus
#

both do not work

sly canyon
#

Tell me something

#

Can you hardcode url: '{% url 'clickPage' %}',for me please?

#

What's the expected out put of this?

drowsy stratus
#

i was expection to pull out cp

#

i made it so that if the url was "cp" the page would be redirected to the same template but it would run some script along with that

sly canyon
#

cp meaning current page?

drowsy stratus
#

yes the url of the current page

sly canyon
#

Let me check JInja documentation to check that out

drowsy stratus
#

what is JInja?

sly canyon
#

'Jinja is a modern and designer-friendly templating language for Python, modelled after Django’s templates. It is fast, widely used and secure with the optional sandboxed template execution environment'

drowsy stratus
#

oh so it is the python in html

sly canyon
#

It's what allows you to build stuff with {{ and { within your templates

drowsy stratus
#

ok 🙂

#

actully, in the python terminal, it tells me

#

[30/Nov/2019 20:08:54] "POST /clickPage HTTP/1.1" 200 669

#

or the post request

#

clickPage was the name of the URL i gave in the urls module

sly canyon
#

@drowsy stratus try {{ request.path }} if you want to point to the current page

#

Anyways, I forgot to ask you

#

What's the purpose of your function?

#

How should the website respond to mousedown

drowsy stratus
#

so I wanted to make a simple test app for learning django that every time i clicked the page, it will tell me how many times i clicked it. I made a model that would store that value, and every time I clicked i wanted it to add to a value in the model. This was just for me to test if my javascript could interact with the python

#

also i changed it and it did the same thing

#

it keeps on loading the default view again and again as well, as i put print() in that method and it writes to the terminal every time i click.

sly canyon
#

You want to update the number of clicks in your back-end, right?

drowsy stratus
#

yup :>

sly canyon
#

Cool

drowsy stratus
#

i just want to see if i can do a simple task

sly canyon
#

But "who" is in charge of storing the number of clicks?

drowsy stratus
#

a model called "pageClicks"

sly canyon
#

Can you paste it?

drowsy stratus
#

i gave it one value called "quantity"

#

and the "quantity" I will add one to, every request that view that i call from the javascript

sly canyon
#

As I said before, I don't know anything about django. But your Route for that View should somehow be able to capture that event, or should be updated by another source, which should interact with your object pageClicks, if I'm understanding it correctly

drowsy stratus
#

yah, I want the javascript to run some python

#

i guess if i can get it to run another way it would be fine

#

i just want to have a way to know that I know how to communicate the frontend and the backend, so i can work on other projects

sly canyon
#

Can you draw your process and what's involved with it?

#

It may help you and me

drowsy stratus
#

ok

sly canyon
#

What interacts with what, in which file, which functions, etc.

drowsy stratus
#

a masterpiece😘

sly canyon
#

Do you want to store it in a database of somekind?

drowsy stratus
#

oh i should of drawn that

sly canyon
#

The number of clicks

drowsy stratus
#

yes that is in a database

#

that could be referenced and edited by the views

#

i just cannot get the javascript to run the clickPage method

#

I cannot get the javascript to respond back to any python

sly canyon
#

BRB, I'm playing a match

winged island
#

how do i save flask.session into a JSON permanently?

#

is this even possible?

winged island
#

never mind, i figured it out. i just saved it into a json inside one of the flask functions so that when that site is accessed, the json is updated

sly canyon
#

Has anyone here implemented Flask-GraphQL views?
I'm getting ModuleNotFoundError: No module named 'graphql.error.base' and indeed when I check the dir here's the result:

fair wraith
#

I’m trying to find a third party tool that can help me create a live chat app with flask. Can anyone recommend any? I would prefer to be less on the js side but if it is that’s fine.

sly canyon
#

@fair wraith Never done, but I think flask-SocketIO is what you're searching for

#

That may help

winged island
#

ok never mind, my solution didn't work

#

i still need help with it

#

how do i save flask.session into a JSON permanently?
is this even possible?

fair wraith
#

@sly canyon ya ik about SocketIO but I use python anywhere for hosting and they don’t support it. So I have to use a third party tool 😦

winged island
#

@fair wraith switch to https://repl.it it's way better

fair wraith
#

I’ll check it out. But is there any well known third party services that provide for a live chat in flask

sly canyon
#

Which kind of session are you talking about @winged island ?

#

A Session from Flask-Session?

winged island
#

@sly canyon no, just whatever comes when i do flask.session

#

idk how it all works, really

sly canyon
#

What kinds of information do you want to store?

winged island
#

im using youtube data api

#

so credentials and state

#

it's already in a dictionary form, i just have to save it before it goes away

sly canyon
#

@winged island

import json
#....
with open('data.json', 'w') as file:
    json.dump(data, file)
winged island
#

right, i know HOW to do it. but wherever i put that code, it either runs AFTER the session has ended OR it just doesn't do anything.

#

i need to find a place to put that code where it'll actually be properly saved

sly canyon
#

Where's your request?

winged island
#

i don't actually know

#

this is my code:

sly canyon
#

You're probably running some javascript request to retrieve data from the API

#

Is session1 storing anything at all?

sly canyon
#

@winged island check what's the output of google.oauth2.credentials.Credentials(ytAuthJson['credentials'])
and googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=credentials), because I'm really not sure what is.

I think you should do something like

flask.session['credentials'] =  credentials

Or maybe

flask.session['token'] = credentials.token

if it's a class object with some attributes

winged island
#

hm

#

yeah

#

but that's not my problem

#

i just want to be able to access what WAS in flask.session before i ended the session, and be able to access it AFTER the session has ended

#

most preferably in JSON format

#

@sly canyon

sly canyon
#

But where exactly in your code is there the varible that stores the information that you want to save?

#

Because I feel really lazy to try reading it all and understand

winged island
#

flask.session is what i want to save

#

everything in there

#

wait, you want to know how the stuff gets INTO flask.session?

#

that happens in lines 87 and 103

#

@sly canyon

sly canyon
#

@winged island but what's the purpose of line 45 then?

winged island
#

i just wanted to see if i could jsonify it myself

#

but it hasn't worked

#

that's why lines 52 and 53 exist

sly canyon
#

@winged island right, but does dict(flask.session) really returns a dict with the session information?

winged island
#

yup

#

it 100% does

#

i've checked

#

i don't want to send its output here because it's got credentials inside, which i don't want to reveal

sly canyon
#

Have you tried

    with open("config/ytAuth.json", "w") as f:
        json.dump(dict(flask.session, f, indent=4)

?

winged island
#

yup

sly canyon
#

What happens?

winged island
#

it depends on where i put it.

#

if i put it inside /app it works sometimes

#

if i put it inside __main__ it doesn't work

#

if i put it right at the top, it doesn't work because the session hasn't started yet

#

wait a second

#

i could just take credentials and state DIRECTLY instead of from the session and just put THAT in a json

#

right?

sly canyon
#

Yes

#

Try saving your state on line 88 and your credentials on line 102

#

just after you receive it

winged island
#

yeah, that sounds perfect actually

#

let me try that

#

gimme JUST a minute

winged island
#

@sly canyon it worked! thank you so very much!

sly canyon
#

NP, U figured this one out yourself

stark yarrow
#

Hey, I built an web app using django+react+postgresql that I intend to run it locally. Should I deploy it to an web server like Apache or run it with runserver --insecure ? An max of 5 people will be using it at the same time. It will not be used online, only on local network. If I should deploy it, which web server do you recommend?

#

Or should I use debug=True, since it will be used only by people on my company

#

and it will be easier to debug if something happens

stiff totem
#

So i am using django-oauth-toolkit in order to provide oauth2 authentication for my android application. Now i have to implement social(facebook, google) authentication. And my workflow should be like when user hits signup with facebook button it does authorize successfully thanks to python social auth. So as it is supposed to be, python social auth does create user and it is fine. Now, this case works fine on side of web user. Problem is how can i handle android user tries to login with facebook?, Do i have to pass facebook authorization token to oauth toolkit?

finite lava
#

I have a search bar in flask. Now I have a submit button to it, which is this line

submit = SubmitField("Submit", validators=[DataRequired()], render_kw={"class": "btn btn-secondary"})

It works but I want that instead of text in the button, which now is "Submit", I want it to be that magnifying glass icon. I tried to substitute the first string parameter with the <img> tag, but that did not work..

narrow linden
#

hi everyone, did anyone use django as back end development ? I wanna ask about the online tutorial resource, where do you find complete tutorial about django ?
because i feel really hard to find django blog

marsh canyon
#

Tutorial on the django docs

#

Or

#

Very very good video

#

U might wanna follow the youtuber also as he got some good content for django

#

@narrow linden

gleaming tartan
#

Hello. Anyone here worked with Flask-SocketIO in production? I have some questions about running a websocket server under a load-balancer...

polar nova
#

How can i use bootstrap themes in flask?

#

Can someone help me

vagrant adder
#

Yes you can

#

Just link it in your templates html and you are good to go

polar nova
#

You have a point but it is not enough for themes in flask

#

How can we use js and css codes in it?

flat cloud
#

every example i have seen is using cache in a single file and i havent figured out how to access it in another.py file

manic siren
#

Can someone help me with this? There are only 2 instances where my function isn't working and I'm having trouble fixing it

native tide
#

@manic siren this is web-developement channel

manic siren
#

I was told by @spare tundra to come here. Sorry about that!

safe garden
#

that's js, so it doesn't belong in any of the general help channels

#

so here would prob be the best place to ask, at least on this server

native tide
#

dude that's not even python, are you serious ?

spare tundra
#

the topical sections have a broader allowance for related things. Granted this isn't really web-dev code its just straight up JS.

safe garden
spare tundra
sly canyon
#

I'm using Flask-Login on my application, but I want to improve authorization on my routes by assigning User.roles to my Users objects and parse something like @roles_required on certain routes to only allow access from users with certain roles, can anyone recommend me a library to deal with that?

muted silo
#

Hello does anyone know a way to search for anything on your own website (localhost) ?

fair wraith
quasi ridge
#

@muted silo I don't think there's any general way

stiff totem
#

So i am using django-oauth-toolkit in order to provide oauth2 authentication for my android application. Now i have to implement social(facebook, google) authentication. And my workflow should be like when user hits signup with facebook button it does authorize successfully thanks to python social auth. So as it is supposed to be, python social auth does create user and it is fine. Now, this case works fine on side of web user. Problem is how can i handle android user tries to login with facebook?, How do i provide oauth2 token with python social auth response?

mild lion
#

HI ,I am developing website in flask,and stuck at point where the results i am getting on from my search i want to display it on next page and i am not able to extract selected any pointers will appreciate

#

for example if user select of hyperlinked item i want to capture and display it on reults page

#

i started something like below

#

@app.route('/Results', methods=['GET','POST'])
def results():
if request.method == "GET":
form = BookReview()

#

ReviewItem =request.args

#

but not sure how to proceed ... 😦

strong prawn
#

hi all!
I am new to this forum
just wondering if anyone tries the gRPC with python?

vagrant adder
#

I'm guessing that's raspberry pi library?

#

Or not

polar nova
#

can somenone help me about theming in flask?

narrow linden
#

@marsh canyon Ok, thanks alot dude

gleaming herald
#

I have chatbot which talks in websocket

from fastapi import FastAPI
from starlette.websockets import WebSocket
import random

app = FastAPI()


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    id = random.randint(10, 10000)
    while True:
        data = await websocket.receive_bytes()
        if data == "Hey":
            print(f"Hey User {id} : {data} Acknowledged :P")
            await websocket.send_bytes(f"Hey User {id} : {data} Acknowledged :P")

            if data == "Hello" :
                print(f"Hey User {id} : you already said Hey :P")
                await websocket.send_bytes(f"Hey User {id} : {data} Acknowledged :P")

        else:
                print(f"Hey User {id} : Start with Hey instead of {data} :P")
                await websocket.send_bytes(f"Hey User {id} : {data} Acknowledged :P")
#

I wanna build a layer over it so even rest request can talk according to each user

#

can anyone provide a better solution

#

Like maybe replacing webscokets with redis to maintain context of each user ?
I tried but it was not working
going in infinte loop
that it was working for one client but not more than one

gleaming herald
#

That's why I tried calling it as a subprocess

#

@crystal rain I dont think web socket sync would solve this

crystal rain
#

what is this in reference to?

gleaming herald
#

This

crystal rain
#

ah

#

yeah no, I have no idea what to do 😬

devout quiver
#

Hi, can someone help me w/ Django?

elfin solstice
#

!ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

polar nova
#

Does someone have any idea about bootstrap theming in flask?

vagrant adder
#

man

#

just link boostrap in your html

#

and you can use it in your html code

polar nova
#

That is for templates

#

I say how can we use gulp file and scss file

#

Can you look this file

#

@vagrant adder

vagrant adder
#

ah scss

#

that's not theming then

#

that's whole custom frontend

muted silo
#

Hello

#

I need some help

#

Is someone available?

round snow
#

Is there an easy way to put a script onto a website? I’ve been using azure but it’s complicated and can’t find anything to help me online

magic prism
long cairn
#

Is it harmful if you leave the /o/applications url open ?

manic tree
#

Hello ! I'm coming from desktop (pyside) application development for CGI softwares (maya, modo, nuke, mari), so my knowledge in programming is very specific to that area. Although I'll need soon to develop a web application for managing our film productions data, so with a quite rich UI. Knowing nothing about web development workflow, I'm a bit overwhelmed by my researches so far. I won't ask which tool I should use, I'm only asking if there is somewhere a simple article that you'd recommend that explain the world of web development ? I read about react/vue/angular flask/django, I see about quite scary stacks, but I don't know nor understand who does what. So if you have a nice article explaining the basics for a slow-learning beginner like me, I'd be thankful 🙂

fair jasper
#

@devout quiver what's your question?

#

@manic tree I don't know any specific articles sorry, but maybe you could begin with looking up what the diff between front-end and back-end is, if you don't already know the difference

maiden juniper
#

Django / Git question: What is the typical "flow" if you need to make a migration and then commit? Do you 'makemigrations' then 'migrate' then add/commit? Or is the add/commit before migrating? Thanks

proper hinge
#

Doesn't migrate just apply migrations to the database

#

and the database of course does not get checked into vcs

#

so it doesn't really matter

#

but I suppose it's good to know your migrations successfully get applied before you go ahead and commit them

final fractal
#

hey guys, I just picked up Flask (we use Django at work and it's a bit of a black box for me, plus it was overkill for what I have in mind). For the Python backend, I use esper (an Entity-Component System). two questions: would you use the database for communicating between the back and the front, or just JSON encoding/decoding? and second, for a text-based game, sort of what is known as MUD or MUSH, would you use DOM or some sort of a canvas-based solution?
I already have a barebones skeleton that uses JSON for communicating and just displays JSON content on the website, but just showing JSON obviously won't scale - I intend to take it at least as far as the Python roguelike tutorial does (Esper example here: https://github.com/abesto/pyrl - so a map, some enemies, player inventory, some usable items, extremely basic combat engine, field of vision and save/load)

odd locust
#

Hey, i've been searching for a bit for this. Does anyone have a solid tutorial that shows how to set up Vagrant to run a python 3-based web server so I can develop locally?

#

I'm a C++ dev, not a web or python dev, if that matters.

#

I was using puphpet for a while, but that was over a year ago, and I'm not familiar enough with configuring that stuff with python (it's puPHPet, after all...) to pick the right settings.

odd locust
#

alright, I found this from 2016:

quasi ridge
#

@odd locust last I checked, vagrant was supsrisingly easy. The tricky bit is choosing a distro.

#

probably best to choose one you're familiar with

#

once it's booted and you can ssh in, then it's just linux; and the fact that it's vagrant is irrelevant

odd locust
#

Yeah I've used it before with php. But not with python.

odd locust
#

I'm mostly on OS X, never on linux.

#

Does anyone here have a preferred vagrant config they use when running a VM for developing web apps built with python?

#

@quasi ridge any thoughts or suggestions?

quasi ridge
#

I've never done it seriously but I think I just slap in ... uh ... Debian? Lemme look to see if I have some notes about what I last used

#

I think centos7, mostly because it's vaguely similar to Amazon Linux, which is what I use IRL

odd locust
#

ok

#

I'm trying to set it up now, but have no idea what i actually need. I know i'm gonna eventually do some database interaction, so probably gonna need SQLite, but no idea on the CRON jobs or Mongo or whatever other options they allow

quasi ridge
#

those are all legitimate worries, but your choice of distro, nor how you configure vagrant, probably doesn't matter much; what really matters is what stuff you install with your package manager after you've got vagrant going

quasi ridge
#

personally I'd make sure I have python3 -- from the package manager, if the provided version is reasonably new -- and pip from the package manager. From then on I'd use pip (or pipenv) to install whatever else you need

#

you might need to install some libraries like ssl or what-have-you, in case you want to install python modules that have C components

odd locust
#

I'm running into this:

~$ pip install --upgrade django
Requirement already up-to-date: django in ./venv/lib/python3.5/site-packages (3.0)
ERROR: Package 'Django' requires a different Python: 3.5.2 not in '>=3.6'
#

I'm trying to solve this error:

#
File "/home/matkat/venv/lib/python3.5/site-packages/django/utils/crypto.py", line 6, in <module>
    import secrets
ImportError: No module named 'secrets'

when I run this line:

django-admin.py startproject authv3 .
#
$sudo apt-get upgrade python3
Reading package lists... Done
Building dependency tree       
Reading state information... Done
python3 is already the newest version (3.5.1-3).
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
#

bah, why can't I get python 3.7

rough laurel
#

Is there anything tricky with creating a task queue, and having those tasks perform web requests, and returning the result of those task requests to the web client?

odd locust
#

any thoughts on this one?

pip install upgrade pip
Collecting upgrade
  ERROR: Could not find a version that satisfies the requirement upgrade (from versions: none)
ERROR: No matching distribution found for upgrade
WARNING: You are using pip version 19.2.3, however version 19.3.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
native tide
#

yes it means u should update because the recuirments aren't meth

quasi ridge
#

@odd locust try pip install --upgrade pip -- that is, use two dashes before "upgrade"

#

also, in order to get python 3.6, you might need to tell apt to use a repository with newer stuff, or even build python from source

#

pretty sure there are alternative apt repos that will have python 3.6

odd locust
#

I mean the fact that the previous version was "none"

rough laurel
#

can I use the same Redis instance for a RQ backing and to cache data? or should those be separate instances?

vagrant adder
#

i would say separate them

rough laurel
#

ok

#

is there an easy way to be notified when a job is done, so I can act on the result? I'm making an app where, the user signs up through a 3rd party sign in, and then I want to pull a bunch of data in repeated requests from that 3rd party.

molten temple
#

Hello, which view in DRF are better? function based or class based?

odd locust
#

Hey does anyone know how to set up VSCode to debug django stuff that was spawned via python3 manage.py runserver ?

#

so I can trigger breakpoints and inspect variables..

odd locust
native tide
#

Hi there, I'm having some issues with flask. when these files are combined into a single module, they work fine, yet when apart I get 404 errors on all of my pages. there is a run.py file, a chatapp directory, and within it init.py and routes.py

#

run.py: ```python
from chatapp import web_app

if name == 'main':
web_app.run(debug=True)```

#

init.py: ```python
from flask import Flask

web_app = Flask(name)
web_app.config['SECRET_KEY'] = 'temporarykey'```

#

and routes.py: ```python
from chatapp import web_app

@web_app.route("/")
def home():
return 'home page'```

#

I am not sure if this is some bug, or I'm making some fundamental mistake here. Google isn't returning anything useful on this. Thank you.

sharp briar
#

as far as I can see, routes.py isn't getting run

native tide
#

thank you, that did fix it. I just figured flask would automatically search for routes.py, as it does with templates in the template directory as a default path

sharp briar
#

nah flask is a microframework - I wouldn't think it would do that

native tide
#

I don't know, maybe a little bit too much django rubbed off on me

#

thanks for your help

lofty matrix
#

In Django or other web frameworks, say someone uploads a video, the server handles resizing the video, then allows the user to download the processed video (made up example). Should that somehow be transfered back to the user through the static file system? (NGINX transfering the file instead of Django/gunicorn), or is it OK to transfer it straight from Django?

#

If the former, how does that work in practice?

cerulean vapor
#

@lofty matrix It sounds like you could just have Nginx handle that part, perhaps by having those kinds of requests fulfilled by a separate subdomain that does nothing but that.

#

Basically, you do the resize job, place it on a file system according to some naming scheme, send the person a download link, and then route it through some Nginx mapping that does nothing but read from that particular file system, etc.

lofty matrix
#

That makes sense, thanks. What if I wanted permission to download that file associated with their account, which exists within django? (so if you sent someone else the link, they could not use it) Could django establish the NGINX connection somehow?

cerulean vapor
#

Are these files things you want downloaded within a particular stretch of time, like a link that expires?

lofty matrix
#

In this example, yea, they would probably need to be deleted after a few days/hours, but in a different one I could see the link being semi-permanant

#

Take google drive for example if you're familiar with it. I can send a link to a file, and when someone visits it, it makes sure that they are authorized to view it, maybe they're authorized to edit it. Then the download happens, and the permissions are a part of that somehow

cerulean vapor
#

As far as permissions go, I think there may be programmability in Nginx that might help with this. I would not be inclined to burden Django with multi-megabyte file transfers all the time (although I suspect the burden would be more about number of connections than amount of data transferred, but I say let Nginx handle what it's best at)

#

I am not as familiar with Nginx as I need to be to give a good answer, I'm afraid, but I do think it would be best to see how you could have Django configure Nginx, maybe even on a URL-by-URL basis, to check for credentials (maybe by way of an API call)

meager anchor
#

problem with having django handle that is that one worker won't be able to do anything else while it's streaming a big file. if you have a slow client, that's awful, and nginx can handle that with ease

cerulean vapor
#

Exactly my thought as well. Django 3.0 now supports async, but I suspect that's not the answer you want to hear :D

native root
#

There is the potential of passing a "key url" that is unguessable, which wouldn't require manually configuring nginx

cerulean vapor
#

I think what he wants is for a user's Django credentials to be the key.

lofty matrix
#

It doesn't necesarily have to be credentials. Maybe it would increment a counter of how many times the file has been accessed. Some sort of processing occurs within django before the file is served. I'm thinking that utlimately it might end up being a unique, unguessable URL that is served by your web server at some level

cerulean vapor
#

So that's the basic answer, I guess :D But yeah, you don't want to tie up Django with serving large files if you can help it.

#

At least not until their async story gets a little more robust.

native tide
#

How do I prevent a logged in user (server/profile/user) from accessing another user's page in Flask. For example if the 'user' user changes the path to 'server/profile/user2' he will be able to see user2's profile. How do I prevent that from happening?

#

I'm using Flask

#

Nevermind, solved!

sly canyon
#

@native tide do you mind sharing your approach?

mortal bear
#

How can i link to another webpage inside an object tag and have the whole page be directed there not just the object tag (Django)

sly canyon
#

@mortal bear can you explain this one further? I didn't quite get it, illustrate if possible or show the result vs the expected output

mortal bear
#

@sly canyon I have a html file with some code and to display this i use the object tag. But whenever i click the link which is inside the object tag the link doesnt redirect the whole page, it will only change the object tag.

#

not really too sure how i can explain this

native tide
#
 from django.db import models

# Create your models here.


class Houses(models.Model):
    street = models.CharField(max_length=30, null=False)
    state = models.CharField(max_length=8, null=False)
    zip = models.IntegerField(null=False, default=1)
    county = models.CharField(max_length=12, null=False)
    neighborhood = models.CharField(max_length=16, null=False)
    apt = models.IntegerField(null=False, default=1)

    def __str__(self):
        return "{}".format(self.street)


class NewLandlordEntry(models.Model):
    # first name of bad landlord
    GOOD = "Good"
    BAD = "Bad"
    GOOD_OR_BAD = [
        (GOOD, "Good Landlord"),
        (BAD, "Bad Landlord"),

    ]
    user = models.CharField(max_length=12, null=False)
    full_name = models.CharField(max_length=16, null=False)
    # last name of bad landlord
    good_or_bad = models.CharField(max_length=5, choices=GOOD_OR_BAD, null=False)
    # current adress of report
    house = models.ForeignKey(Houses,  on_delete=models.CASCADE)
    # all known adressess of the bad landlord

    def __str__(self):
        return "{}".format(self.full_name,)```
#

I dont understand why I get this error?

#

its django Im using the restframwork

#

that error happens when i run migrate

mortal bear
#
class getVals {
    constructor() {
        this.sForm = document.getElementById("SearchForm");
        this.getRequest = "?&";
        this.getNext = false;
    }

    checkVals(ele) {
        if (ele.checked) {
            this.getNext = true;
        } else {
            console.log(ele.checked)
            this.getNext = false;
        }
        if (getNext) {
            this.getRequest += "&" + ele.name + "=" + ele.value;
        } else {}
    }

    submitSearch() {
        Array.prototype.forEach.call(this.sForm.elements, this.checkVals);
        // for (var i=0; i<this.sForm.elements.length; i++) {
        //     checkVals(this.sForm[i]);
        // }
        console.log(this.getRequest);
        return this.getRequest;
    }
}

New to js, why do i get the error : cannot set property getNext of undefined?

meager anchor
#

@native tide can you show the full traceback?

native tide
#

@meager anchor ye

#

wait nvm

#

i forgot i fixed that

#

but im stuck on something else

#

Request Method:     GET
Request URL:     http://127.0.0.1:8000/landlords/
Django Version:     3.0
Exception Type:     OperationalError
Exception Value:     

no such table: landlord_data_houses

Exception Location:     /home/jacks/.virtualenvs/Bad_landlord/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 396
Python Executable:     /home/jacks/.virtualenvs/Bad_landlord/bin/python
Python Version:     3.6.9
Python Path:     

['/home/jacks/bad_landlord/Bad_landlord/bad_landlord_api',
 '/usr/lib/python36.zip',
 '/usr/lib/python3.6',
 '/usr/lib/python3.6/lib-dynload',
 '/home/jacks/.virtualenvs/Bad_landlord/lib/python3.6/site-packages',
 '/home/jacks/.virtualenvs/Bad_landlord/lib/python3.6/site-packages/setuptools-40.8.0-py3.6.egg',
 '/home/jacks/.virtualenvs/Bad_landlord/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg']

Server time:     Sat, 7 Dec 2019 00:57:21 +0000```
#

thats what pops up in my browser when i try to admin the data

#

http://127.0.0.1:8000/landlords/

#

this url

#

lol

#

i fixed it

#

sorry

meager anchor
#

forgot to run migrations? :D

#

no worries

#

sorry for the delay!

native tide
#

How can i pull the ticket count to selenium on python?

#
                    to
                    <span id="listv2_f25399ce1bed04102363fe6edd4bcb5e_last_row" style="margin-left: 1px; margin-right: 1px">2</span>
                    of
                    <span id="listv2_f25399ce1bed04102363fe6edd4bcb5e_total_rows" style="margin-left: 1px;">2</span></span></div>```
rigid laurel
#

I want to make a Flask project that lets people upload a file and then run Markov Chain text generator on it, and return some amount of generated text. Thats pretty easy to write the code for - but I want to do as much of it as I can to a professional standard - as such I have no idea how to structure the project, are there any good resources which can point me towards a sensible project structure?

fair jasper
#

you could look at how cookiecutter-flask is structured

rigid laurel
#

Looking at it, I understand what most of the individual things are doing - but I have no idea why its structured the way it is

ashen trench
#

i got this error in django

#

(1091, "Can't DROP 'link'; check that column/key exists")

#

what do i do

#

i removed one of the fields, it was long before, but now i am getting this error while trying to migrate

queen ivy
#

single or multiple repositories for microservices?

north perch
#

this is somewhat a cry for help and also just general whining: does anyone else find the flask infrastructure extremely confusing? It looks like it's in a state of flux where most of the docs (and plugins, and extensions, etc) still reference the old, non-factory style architecture ... but the tutorials and quickstart insist you use the factory method. Makes it sorta hard to transition from the quickstart to doing anything useful, or I am ... really just very stupid

#

I followed along and implemented the "flaskr" tutorial in the docs using the 'flask run' development server for testing, and I want to test deploying with uWSGI but I'm not actually sure how to bridge that gap right now and can't quite find info in the docs that gets me cooking there

#

it looks like uwsgi probably does not understand the magic method create_app in the same way that flask run does, so I need some glue code there, but I'm not sure what sort of glue to write, exactly

#

if anyone has some good reading links or some help to throw my way, I would be really appreciative!

gilded siren
#

@north perch Flask is one of the simplest frameworks for python IMO. Different frameworks work better with different people depending on their preferred workflow. Many people swear Django is a breeze and very streamlined, yet for me it is one of the most confusing web frameworks across any language I've developed web apps in. I prefer a very barebones DIY starting point that I can build upon, and tweak to my liking. So i tend to use express for node.js apps, and flask for python apps.

For your specific issue
For Linux, Mac, Linux Subsystem for Windows, Git Bash on Windows, etc.:

export FLASK_APP=myapp
export FLASK_ENV=production
flask run

For Windows CMD, use set instead of export:

set FLASK_ENV=production

For PowerShell, use $env:

$env:FLASK_ENV = "production

Then you can wrap your flask app in something liek gevent, flask-socket.io, etc for testing

north perch
#

specifically I'm trying to figure out what the "right" way to deploy an app with uwsgi is when flask uses the app factory method

#

I got uwsgi -w flaskr:create_app() to work but am not sure if this method has any drawbacks that I might not be aware of

#

most of the tutorials do not assume you are using the app factory method

gilded siren
harsh carbon
#

Does anyone here use FastAPI

native tide
#

in jinja2 templating, can you do logic using {{ }} and {% %} syntax inside of an included template?

#

include as in the keyword as opposed to block or extends

#

if so... do you have to render that includes html file before rendering the more base level html?

vagrant adder
#

yes you can TLS

#

jinja works in included files as well

hoary spruce
#

is this possible?

vagrant adder
#

Mysql and sqlalchemy are not the same thing

#

Mysql is a database that hold data and sqlalchemy is software which commnicates with your database

#

You can use both

haughty saffron
#

Is there some way to make my bot create a new file on my website and put code on it?

cyan wolf
#

yo so

#

just wondering

#

when you select a link from the dropdown, how can i get it to close the dropdown and just show the page?

quasi ridge
#

@cyan wolf I dunno about anyone else, but I for one have no idea what you're talking about

cyan wolf
#

ok so

#

this is my website

#

that is the dropdown

#

if i click on about, i am routed to my about page

#

the top bar is kept open when the page is opened

#

how do i make it close when im routed somewhere

#

wait looks like it already does

#

but now half my dropdown isnt routing

quasi ridge
#

no idea; it probably depends on whatever stuff you're using to generate that page

cyan wolf
#

python

#

flask

quasi ridge
#

I imagine you're using more than that; neither of those contains code to display the (rather-nice-looking) web page you showed earlier

rigid laurel
#

Yeah, it sounds rather like a CSS/HTML problem specific to your code

#

I imagine you can find a boilerplate type thing on w3schools that you could copy over if thats the issue

west mulch
#

Im using the latest bottle on pythonanywhere. Im having a problem with my website. Its not loading this part of the site everything else is good. Is there something wrong with my python code. I need some help im new to this.

#

I ran this through pycharm and the python code works I have no clue what is wrong with this

barren delta
#

Who read Django channels book ?

native tide
#

Hello

#

I have a question about adding new objects from API to my database. I have a first table League, that have a leagues objects and another table - TeamInfo. What is the best way to do this? In TeamInfo I have FK from League

mossy shell
#

Hi,
I want to implement social login feature in a django backend application. I have used dejango_rest_framework. Which librery would be best for me to do that job with a proper documentation?

native tide
#

@mossy shell try django built in Token authentication, it works very good

quasi ridge
#

I hope it's easier to use than OAuth ... never could figure out how to do that

vagrant adder
#

Not to advertise or anything but Engineerman posted a really good video about OAuth2

#

and how it works

quasi ridge
#

I can't see anything wrong with that kind of "advertising"

vagrant adder
#

just saying, mods here are really by-the-book and i can't really blame them

undone lichen
#

Hey guys, I'm using Flask and I'm trying to create a cookie for my parent domain. I added dev.xyz.com to my hosts file and I'm trying to create a cookie for .xyz.com, however when the cookie is created, it just uses dev.xzy.com and not what I set. I'm able to create the cookie correctly with JS, so this makes me think there is some config variable I need to change, but I'm just not sure which one. Thanks! 🙂

heavy coral
#

I also have a flask related question but I am unsure how to go about explaining it. I want to alter a python script I already have to run by me inputting a url into a search insert on the flask page - and return the response not as an html table, but as an input form with ability for me to edit anything I need to and submit to be added to a database table. I have the code that I based my currently working python script off of but apparently the way that is written, it returns the json and I'm having trouble trying to figure out how to alter things so it does what I want.

#

Links available for both script I based stuff on and my current script i run manually in the python console if desired//needed

hollow flower
proper hinge
#

I've used it before (albeit for a GUI app)

hollow flower
#

Huh, for some reason I didin't come across that one yet.

proper hinge
#

It may be getting unmaintained but it was working when I used it in March

hollow flower
vagrant adder
#

@hollow flower flask_wtf had recaptcha field and works seamlessly

hollow flower
#

I don't want to use Google's phishing services, thank you.

#

I'm trying to find a solution which is not Google tied nor tied to any 3rd party services, like Google's recaptcha and you cannot use it without JavaScript.

flint depot
#

👀

native tide
#

talk about paranoid

flint depot
#

Lil bit

steel tiger
#

I mean for capcha they do have a lot of trackers so sort of understandable

#

That and it's contributing to Google ml if you care about that

#

But capchas need trackers to make it easier to see if you're a human or not

vagrant adder
#

@native tide lmao

restive bloom
#

Anyone here into WebRTC?

#

I'm trying to figure out what my options are for establishing the initial connection

#

I'd like to automatically connect to other discord users I'm in a voice channel with. It seems like Discord could potentially provide a signalling server, but I'm not sure if any of their APIs could be utilized as one (probably not?)

zealous siren
#

like direct connection?

restive bloom
#

Yea, once the connection is made I wouldn't want any server to be involved

#

I'm seeing if the Rich Presence invite system could do the trick atm.

mortal bear
#

Anyone know if its possible to embed one of these into a website?

dim socket
#

Hello everyone, I am new to django, I want to implement a feature in which the web app will take in the user's location and plot it on map and also display other users nearby. It would be very helpful if anyone points me in the right direction
Thanks

last basalt
#

Try to google Django geolocation services

#

Maybe you will find something usefull

cyan wolf
#

yo so

#

just needing small help with css

#

now im trying to make my dropdown actually go down when you hover over it

#

can anyone help me identify where the navigation route code is?

#

id also like to make part of the dropdown a bit smaller, so i also need to identify where to find the bit to chuck it in

native tide
#

hi, I have a question regarding socketio and deploying to an ubuntu server. My code works perfectly fine in my dev environment, but I get an error on the last gunicorn command to start it.

#

run.py to start it: ```python
from app import web_app, socketio

if name == 'main':
socketio.run(web_app, host='0.0.0.0')```

#

project init: ```python
from flask import Flask
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy

socketio = SocketIO()

web_app = Flask(name)
web_app.debug = True
web_app.config['SECRET_KEY'] = 'xxxxx'
web_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
database = SQLAlchemy(web_app)
from .main import main as main_blueprint
web_app.register_blueprint(main_blueprint)
socketio.init_app(web_app)```

#

and server logs: ```(venv) mark@server-demo:~/squintsyfinal$ gunicorn --worker-class eventlet -w 3 run:socketio
[2019-12-11 18:12:53 +0000] [10405] [INFO] Starting gunicorn 20.0.4
[2019-12-11 18:12:53 +0000] [10405] [INFO] Listening at: http://127.0.0.1:8000 (10405)
[2019-12-11 18:12:53 +0000] [10405] [INFO] Using worker: eventlet
[2019-12-11 18:12:53 +0000] [10408] [INFO] Booting worker with pid: 10408
[2019-12-11 18:12:53 +0000] [10409] [INFO] Booting worker with pid: 10409
[2019-12-11 18:12:53 +0000] [10410] [INFO] Booting worker with pid: 10410
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Application object must be callable.
[2019-12-11 18:12:54 +0000] [10408] [INFO] Worker exiting (pid: 10408)
Application object must be callable.
[2019-12-11 18:12:54 +0000] [10409] [INFO] Worker exiting (pid: 10409)
Application object must be callable.
[2019-12-11 18:12:54 +0000] [10410] [INFO] Worker exiting (pid: 10410)
[2019-12-11 18:12:54 +0000] [10405] [INFO] Shutting down: Master
[2019-12-11 18:12:54 +0000] [10405] [INFO] Reason: App failed to load.

#

its a starter project to learn this stuff and I'm just struggling to fix this. I'm pretty sure the problem is somewhere in run.py regarding the socketio variable, but I'm not sure.
And to reiterate, this code runs perfectly fine locally

native root
#

Are you starting it locally via the same gunicorn command?

#

Because that won't work-- gunicorn must be passed the flask app, not the socketio adapter

#

In your case, that's web_app @native tide

native tide
#

locally, I was just using the flask development server, not gunicorn. but changing it to web_app now makes it run, I think all thats left is for me to add socketio config data into nginx so this is a huge leap forward in progress. I thought I'd have to send socketio and not my flask app because it is "wrapped" with socketio

#

but thank you very much for your answer

native root
#

👍

bold mortar
#

hi

vagrant adder
#

Hi

bold mortar
#

i just wanted to know can we use React.js and Angular.js with Django?

#

simultaneously

vagrant adder
#

Yes

#

Both do different things

bold mortar
#

i know.i will learn one of them

ionic sequoia
#

Can Django be used to build an institutional level trading platform, or will it be too slow compared to Java?

native tide
#

@mortal bear I believe discord has their own embed you can use

mortal bear
#

Do you know where i can find that? The inbuilt widget one doesnt have ana invite code

#

i dont think

native tide
#

it should

#

You can also just take a screenshot of an invite link and turn it into an image, not the most responsive, but that's how discord did it in emails lol

mortal bear
#

hmmm ok ty

unique willow
#

Hi guys,
I have a quick question. I am developping a web site Flask based, however I have a little issue with my html bootstrap code as my nav bar is always displayed in vertical position whatever the class I use or the CSS I use. I even tried to override by css but no result have anybody face this issue before ?

heavy coral
#

Do you have a snippet of the CSS you're using?

sly canyon
#

@unique willow try using the dev tools in your browser and inspect the navbar element in order to see what's causing it to behave like that. That way you can see the Styles applied to it and the source files containing those. You can then delete or alter the code to know what to do in order to fix it.
You may be using class = d-flex flex-column as a wrapper and it's causing it to be a vertical container

dawn heath
#

is anyone good with html / css?

unique willow
#

@sly canyon thanks i will do that right now

solar hatch
#

Best Django tutorial on YouTube ????
What do you recommend?

#

To get started

dim socket
#

@solar hatch Corey Schafer

#

How do I store data from google map api in JS to a django form field?

unique willow
#

@sly canyon thanks a lot you were right the it was flex colomn

vestal estuary
#

Anyone got a suggestion for a cms? Thinking mezzanine/dajango-cms/wagtail.

thorny rover
#

so say i have computer a which is local, and a remote computer b. theyre connected by a vpn tunnel. computer b has a server on it with a web client.
from computer a, i can enter the ip and port and connect to that servers web client. but i can not use the dns entry to connect. but on the server itself i can use both the ip and the dns to connect. i can also from the local computer use the dns or ip to connect to any of my other servers web clients, any idea why?

local -> direct ip -> server [✓]
local -> DNS -> server [X]
server -> direct ip -> server [✓]
server -> DNS -> server [✓]

any ideas?

bleak bobcat
#

What does the DNS resolves to ?

thorny rover
#

as in what ip does it go to? same one im manually entering which is 10.104.55.101:8080

bleak bobcat
#

so 10.104.55.101

thorny rover
#

well yes, still have to add 8080 to the dns

bleak bobcat
#

That's weird. Just for sanity, on local what's the result of you pinging the DNS ?

thorny rover
#

cant find it

bleak bobcat
#

Well here's your problem. Dunno what DNS server you're using but either they haven't full propagated yet or you're not using the same

thorny rover
#

we think we found it, it looks like the guy in charge of adding the new static ip to the filter policies on these remote routers didnt reboot them after and that is causing this

zealous siren
#

just for education, DNS doesn't care about ports

#

hostname -> IP is all DNS handles when talking about HTTP, everything else is taken care of outside of DNS

hoary spruce
#

So I'm trying to figure out a way to display different froms on my page. Depending on what the user selected in a dropdown list, using Flask.

#

Would this be possible without having to have to user click a button to send the selected dropdownlist value?

unborn vine
#

I have a webpage where my Django backend is creating a bunch of <a href> links via a Jinja template. Based on whichever link the user clicks on, I want to make a jQuery AJAX call to a specific URL, but I need to differentiate which <a href> link the user clicked on. In Javascript, you'd do something like onClick="myFunc(x,y)", where x and y are unique per <a href> - how do you do this in jQuery? I get that I can figure out what they clicked on by the $this - would I just store a couple of variables in the <a href var1="x" var2="y"> and access it that way?

native root
#

$(selector).click(function() {

#

If you have a custom tag on the href, $("[my_custom_tag]").click()

cursive barn
#

@native root Sorry for the ping but is it normal to find GoogleDriveDS under Application on a website

#

And I have the option to delete the database

unborn vine
#

Thank you!!

native root
#

You mean by going to website.com/Application/GoogleDriveDS?

#

No, not normal

jovial vapor
#

Hello

#

anyone here

#

ever use Nginx?

native root
#

!ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

native tide
stuck bramble
#

if anyone is familiar with selenium, is there a way to wait for an element to change (not load in), then continue with the code?

mossy maple
#

A rather simple question that I can't seem to find the answer to. How can I access the body of a POST request within python when executed as cgi under apache?

polar wasp
#

@mossy maple use the cgi module

#

if you're not doing that, post request body is in stdin though

rigid laurel
#

Does apache/whatever really just feed requests to stdin?

#

That's probably the kind of thing I should know

polar wasp
#

that's how CGI works

#

bunch of stuff goes in environment variables, request body goes in stdin

rigid laurel
#

Oh sure. I didn't realise that, definitely the kind of thing I sold have known

polar wasp
#
  1. Data input to the CGI script

    As there may be a data entity attached to the request, there must be
    a system defined method for the script to read this data. Unless
    defined otherwise, this will be via the `standard input' file
    descriptor.

    There will be at least CONTENT_LENGTH bytes available for the script
    to read. The script is not obliged to read the data, but it must not
    attempt to read more than CONTENT_LENGTH bytes, even if more data is
    available.

mossy maple
#

Random, thx read from stdin

native tide
ripe pecan
#

anyone used FastAPI before?

glad topaz
#

@ripe pecan
i started to use it few days ago

ripe pecan
#

are you liking it?

glad topaz
#

i really like it

#

i started at flask, then had to move to async so used Sanic

#

and now trying fastapi

#

it feels elegant, you have everything and it just works

#

some of the docs could be better but it's still work inprogress

ripe pecan
#

Yeah, fair enough. I've mostly only used Flask and Django

lavish prismBOT
#

Hey @native tide!

It looks like you tried to attach a file type that we do not allow. We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv.

Feel free to ask in #community-meta if you think this is a mistake.

native tide
#

I am following along to Python Crash Course, I am currently on Chapter 20. I have done some styling in base.html and index.html and when I went to run my file to test the look and feel I get the following error. The total line count of the error is 72 lines. I will upload the error to github so you guys can see it more in depth. Unless the line below explains.

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'

oblique scaffold
#

so a friend needs a mobile/responsive? WEB UI that can be used from mobile or tablet or PC to gather some basic data . I was thinking of using on the server Python/Flask/MySQL any guidance or other items I need in my stack? I have a windows 2012/R2 server so pointing the DNS/name to that IP will be easy.

vagrant adder
#

it depends how big is the website

#

if it's really big, django is the way to go

#

react or vue is good for frontend

jagged drift
#

Saki: I'm interested in learning flask, but how big would be "too big for flask"

quasi ridge
#

I don't think "big" is the issue

#

django has a ton of features, particularly database stuff; afaik, flask is leaner. I personally have only used flask for routing

vestal estuary
#

From experimenting with each, I have noticed that with flask you basically have to build a lot of the functionality that Django has by default. With Django you basically have to play by its rules, often by overriding it. However, it saves a ton of work compared to flask because that stuff is already coded. It is just a matter of learning it.

#

That said... One thing that royally irritates me about django is that I feel like it violates the DRY principle. You want to make a form? Well you'll need to create a models.py (and also used in migrations file) and state every field with their types. Then you make the forms.py which you again have to refer to the model and specify each field. Then, in the view, if there are any special cases you have to specify them once again. It's a pain. And it makes me feel dirty when I do it.

native tide
#

What's the DRY principle?

native root
#

Don't Repeat Yourself

#

Generally, it means that you should not be writing the same thing in two places, but more abstractly it can mean "If I want to change a distinct detail, that detail should be specified in only one place"

native tide
#

Ah, I see now

#

so like, don't have duplicate code

solar hatch
#

Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 16, in main
) from exc
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did
you forget to activate a virtual environment?

C:\Users\joodh\OneDrive\Desktop\web\pollster>
how do i activate pipenv
???
any help

vagrant adder
#

@jagged drift can you describe your project in 2 sentnces

jagged drift
#

Saki: I was thinking of using it to make a portfolio site.

vagrant adder
#

portfolio and nothing else?

#

okay flask would be just enough for it

dawn heath
#

how can I remove parallax effect ?

languid kite
#

Hello, using python version 3.8 , django 2.2,
i am beginner learning django building project by following tutorial, everything going fine but suddenly my admin page refuse to connect 'This site can't be reached' but my blog localhost connects fine , any code i run to refresh my settings or which approach i shall take? Thanks

#

@solar hatch to active your pipenv run this :
pipenv shell

patent cobalt
#

To clarify, the admin pages used to load, but now it suddenly stopped working?

languid kite
#

yeah my latest actions is i created a model , render it with the views.py

#

also when i run the server , the terminal keeps sending this message over and over:

System check identified no issues (0 silenced).
December 16, 2019 - 17:34:23
Django version 2.2, using settings 'testProject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Watching for file changes with StatReloader
C:\Users\azzam\Desktop\django1\pages\models.py changed, reloading.
Performing system checks...
languid kite
patent cobalt
#

I'll have a look.

languid kite
#

thanks , at the time i really couldn't figure it out , i re making the project and will see if it happens again

patent cobalt
#

Is the project structure you're using the same as suggested in the tutorial?

#

@languid kite I've cloned your repo and I can access your admins page just fine

#

So, something else is going on

#

You can try clearing the cookies belonging to that localhost site

languid kite
#

Yes just the same , will clear the cookies and try again , thanks alot @patent cobalt for the help

languid kite
#

all worked now 👍 , thanks again

cyan wolf
#

Hi

#

getting an error from my python/flask based website:

#

only traceback is to the last line of this code:

#
@app.route("/")
@app.route("/home")
def home():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
    return render_template('home.html', posts=posts)```
#

this is only an error with my new code, which ive made add a collection of all user post's individually viewable with their profile

#

ping me if you have any ideas on how to fix this, or if you need some code

sly canyon
#

@cyan wolf reboot your running process

cyan wolf
#

Will do

sly canyon
#

You probably have debug mode on and have re-done some stuffi n your code

#

And you're probably using flask-user

cyan wolf
#

Yeah I have debug on

#

Always helps

sly canyon
#

I think you can list running processes with pgrep -f python on bash

#

Then just kill -9 [id]

#

and try flask run again

#

If for some reason there's still a flask task running in the background

cyan wolf
#

Right

#

I'll have to do that when I get home but thank you!

sly canyon
#

Cool, GL

cyan wolf
#

Cheers

cyan wolf
#

@sly canyon just did that, booted perfectly! Thank you again!

sly canyon
#

@cyan wolf Cool! Glad I've been able to help

cyan wolf
#

👍

fast quartz
#

with inputs, what's the difference between Name and ID?

#

like something like this:<input type="email" name="Email" id="Email" />

native root
#

id is the HTML id you can access via javascript and css

#

name is the name that it will be submitted as

#

You are not permitted to have duplicate id's, but you may have duplicate name's

#

Radio buttons, for example, use the name attribute to link to each other, and the Razor Pages C# web framework merges elements with the same name into a list of values on the backend side

#

I believe flask's WTForms does it similarly

fast quartz
#

it needs to have a name to be added to the URL/GET method right?

jagged drift
#

So... I have a CRAZY idea but I'm having trouble installing everything to make it work.

#

Python + (some sort of backend web server framework) + QtWebEngine + Brython...

native tide
#

Hey, I don't know if this is the right place to ask, but can someone help me on this? I have some software I'll be coding with Django, and I want to host that software on a server and rent it out to people on a month-by-month subscription. So software as a service basically. What I'm wondering is what e-commerce platform I should use for this. I know there's platforms like WagTail, but it seems like a huge waste of time to re-invent the wheel and build a website from scratch using wagtail. It seems easier to just build a site to handle the account registration/subscriptions with something like Wix/Shopify, and then use an API in Python to authenticate through those services and confirm the subscription is valid.

I've been googling this for weeks and am stumped. Can anybody point me in the right direction?

quasi ridge
#

I'd be surprised if AWS didn't have something to help with that, but a) it might be pretty complex, and aimed for larger businesses; b) I have no idea which of the eleventy bazillion of their products it would be

ashen trench
#

@patent cobalt How do you guys manage the api tokens, like where do you store them. text files seems unreliable

patent cobalt
#

I'm not intimately familiar with the devops part of our set-up, but we use salt to expose our secrets to just the places where those type of configurations need to be known

ashen trench
#

i have a refresh token that expires each 24 hours and an access token that expires each 5 minutes

#

confused what to do with it.

#

Problem could be solved if i use a separate database to store both of them , but some says then what's the point of api

patent cobalt
#

So, the tokens give access to your own api?

ashen trench
#

the trick part is i need to keep updating them at regular intervals, if i use .env or store with in the running instance there is a chance for the bot failing all together if the code by chance restarts

#

yeah

patent cobalt
#

Okay, we use a way of authenticating the bot to the API that has a longer lifetime

#

more similar to how Discord lets bots authenticate

ashen trench
#

the website exposes the api , it deals with my main database.

#

i use rest. so i can set the refresh token to never expire ?

patent cobalt
#

How you can do that probably depends on the back-end you're using. We're using Django REST Framwork for our API.

ashen trench
#

I am too

patent cobalt
ashen trench
#

Oh i was using jwt

#

Thanks \

hollow glacier
#

Using flask. How would I go on about making a todo app with subtasks? Example:
Take out the trash // maintask
Plastic // subtask
Recyclabels // subtask

vagrant adder
#

make a table task

#

and a table subtask

#

and relation ship 1 to many between then

#

many subtasks per one task

hollow glacier
#

Thanks!

vagrant adder
#

👌

hollow glacier
#

Is it a bad idea to nest functions in your route to make the code cleaner?

#

Or is there a betteer way to make your routes function cleaner?

#

Using flask btw

vagrant adder
#

uhh

#

can you show the code?

hollow glacier
#

It's not really a question for how to

#

So I don't have any code for it right now

#

But if I do. Do I still separate stuff with functions and if so where do I put the functions?

#

@vagrant adder

vagrant adder
#

it depends what kind of functions we are talking

hollow glacier
#

Let's say I want to do something with one set of users. DO I put the code part in a function?

vagrant adder
#
@main.route("/")
def index():
    data = do_something(something)
    posts = Post.query.all()
    return render_template("main.html", data=data, posts=posts)
#

this is accepted

hollow glacier
#

I was thinking something like:

@app.route("/")
def index():
    def do_somthing(user):
      user.status = new_status
      user.mood = new_mood
    return render_template("main.html", data=data, posts=posts)
#

If that makes any sense

vagrant adder
#

ah so that

#

not really

hollow glacier
vagrant adder
#

for side functions like do_something()

#

and such

hollow glacier
#

ah ok

#

thanks

sly canyon
#

@ashen trench store it in environment variables

dawn heath
signal karma
#

What do you use to host a Python API? Can I use nginx? Any recommendation?

surreal kayak
#

I used nginx/pm2 to host a flask app for a year until I moved the app codebase to TS/node for front/backend code continuity

vagrant adder
#

Gunicorn + nginx is a good combo

solar hatch
#

Hi
I am currently learning Django
Can anybody suggest me any Django projects for beginner or to get started

marsh canyon
#

make a dictionary

#

or todo app

random kiln
#

Hi. I am learning flask (and still quite new to programming and to python).
I added a feature to one of my projects: a admin can upload a file, the file will be validated and cleaned, then sent to be processed. This process take quite a long time (from a few minutes to a couple of hours). I would like to 1/ let the function run in the background 2/ make it possible for the user to follow the progress of the function.
When I google around, most people suggest using Celery (or Redis). I don't want to use that for this particular project, as it's only for a specific function, that only the admin can start, and that should be used only like once a month. It looks to me that opening a new thread should be the best option, but I can't find good guide or example. Could anyone point me to a direction?

#

I was thinking maybe using asyncio, but my head hurts

#

(to be more specific, the file will contain a large list of items (json, xml, csv), and the process will fetch additional data using various api or scraping. It takes a lot of time, but shouldn't be a problem to follow the progress.... like "now fetching infos for item 1 on 780", etc.)

signal karma
#

@vagrant adder do you need nginx if you're already using gunicorn? 🤔 I mean are those 2 not solving the same problems?

solar hatch
#

Do I need to learn JavaScript for Django ????

fair jasper
#

@solar hatch if you're doing front-side stuff, then probably, at least the basics

#

depends on what you're working on really, but you can definitely create a JS-less django app without problems

marsh canyon
#

@solar hatch

vagrant adder
#

@signal karma not really

#

Depends on your use case

solar hatch
#

Ok

oblique scaffold
#

is there a tool I can use to build a mobile UI so I don't have to write the CSS/HTML that I can than use with my webserver running python and Flask for the routes?

wild thunder
#

guys, having a little problem with html and css

my elements are not positioning right, i guess i'm putting it wrong in html setting divs

#

hey guys, i'm new at html + css and i'm having a little problem on positioning blocks on my page, i mean, i end up achieving, but the margins are all unequal
i create a div called box, then i set width and height. this would be the main frame, holding everything inside it, but when i create another div, let's name box-left and another named box right, they both should be side to side, i put it inside like :

< div class="box">

<div class="box-left">
</div>

<div class="box-right">
</div>

</div>

#

consider that the box right have a float to be at right

#

when i continue adding elements, they start to be crazy

signal karma
#

@wild thunder use flex for layouts. And divs are display block so it'll be vertically aligned. You need to use span or display inline for having elements aligned horizontally. But really, if you do not have IE requirement, use flex for everything. (Kinda)

dawn heath
wild thunder
#

@signal karma thanks bro, i'll study it!

native tide
#

Hey, I have a question regarding environments utilizing both Django and React. Pycharm and Webstorm have their own features for each respective language/framework... how do other people approach this? Do you simply have both programs sharing the same directory? Thanks.

signal karma
#

I presonally use VSCode for everything, not sure what PyCharm is adding to Python that VSCode can't do. 🤔

native tide
#

Hey, I don't know if this is the right place to ask, but can someone help me on this? I have some software I'll be coding with Django, and I want to host that software on a server and rent it out to people on a month-by-month subscription. So software as a service basically. What I'm wondering is what e-commerce platform I should use for this. I know there's platforms like WagTail, but it seems like a huge waste of time to re-invent the wheel and build a website from scratch using wagtail. It seems easier to just build a site to handle the account registration/subscriptions with something like Wix/Shopify, and then use an API in Python to authenticate through those services and confirm the subscription is valid.

I've been googling this for weeks and am stumped. Can anybody point me in the right direction?

quasi ridge
#

@native tide I think you asked this before. I'd expect AWS to have something.

native tide
#

Sorry it sunk other under answers and I couldn’t find it so I didn’t know if it got answered

#

@quasi ridge

#

Looks like they do have SaaS servers but it doesn’t allow you to do it through your own website, it’s meant for large businesses it seems

hollow arch
#

hey

#

how to trigger a file or archive download using django

bleak bobcat
#

Change the response headers according to the filetype you wanna serve

cunning imp
#

Hey, not sure if this is the place to post, but I'm a 24 yr old guy who has been on computers since I was 4 years old. Its been my dream to program, but I am only just getting into it now, juggling a fulltime job. I have 10 hours free when I come home, (I'm always on the comp.)

Web Development looks fun for now, but is there anywhere I could start to expect some sort of income, of course it won't come right away, but what would be my best bet, I could post services etc, looking to quit my job soon, depression/anxiety is killing me

#

Thanks all ❤️

#

I love Python btw if that could helo

#

I also know it depends on your ideas etc, but I could offer a service building custom themes or something

wild thunder
#

hey guys

#

i'm having a little problem with flex

#

could someone give me a hint

#

please check those 2 blocks with 01 and 02 content

#

i'm using flex in the white frame behind them

#

to put them both side to side

#

but they keep going one over another

native root
#

They can't go over each other unless you're using a transform: translate, negative margins, or position: to make them do so. But if you haven't specified margins they could be just shoved right against each other

wild thunder
#

<div class="structure">

        <section id="estrutura">

            <article class="main-info"> 01 </article> <!-- the bigger block should be left -->
            <article class="user-on"> 02 </article> <!-- the bigger block should be right -->
    
    
        </section>
    
    
    </div>
native root
#

If you have a third element in the flexbox it could conceivably look like that

wild thunder
#

this is the html

native root
#

hm. K

wild thunder
#

i`ll take the css part

#

one sec

#

i`m 3 days on css+html

#

still shitty code

#

can i send all the CSS code?

#

it's not too big

native root
#

!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.

wild thunder
#

the colorstrip is the color in the top part of the page

native root
#
position: absolute;
#

That's on both main-info and user-on

#

And as far as I can tell, doesn't need to be on anything here

wild thunder
#

but if i put relative, they become a line

native root
#

Isn't that what you're going for?

wild thunder
#

no, i want them to ocupate 12%

#

it's not accepting percentage as height

#

i want these 2 blocks to be 2 containers

#

the idea is ok

native root
#

Right

#

So this is a separate issue

wild thunder
#

the problem is : the heigth

#

yes

native root
#

% height is relative to the height of the parent element, or the nearest one without height: auto

#

But here, you've not specified height on anything

#

so it goes all the way up to the body tag, and that also has height auto

#

so it doesn't set the height

#

If you're aiming for something that's not going to scroll, you can set the body+html tags to height: 100%, and that would work. Or, you could use vh as your unit, which means "percent of height of browser window"

wild thunder
#

.main-info { /* Inside Structure */

width: 78%;
height: 13%;

margin: 1%;

background-color: rgb(197, 197, 197);

border: 1px solid black;
order: 1;

}

.user-on { /* Inside Structure */

width: 21%;
height: 13%;

margin: 1%;
margin-left: 0%;

background-color: rgb(197, 197, 197);

border: 1px solid black;

order: 2;

}

#

they have heigth, based on the ".structure"

native root
#

Which has an auto height, so it keeps looking upwards

wild thunder
#

i changed to 96%

native root
#

which then makes it 13%, of 96%, of the body? Which is still auto

wild thunder
#

stills the same

#

how can i make these 2 boxes become 13% of structure?

#

that is the white frame

#

?

native root
#

<section id="estrutura"> needs a height: 100%

wild thunder
#

shit, such a mage

#

it does work

#

thank you man! really

native root
#

👍

wild thunder
#

i was like 1 hour trying to figure it out

native root
#

I'm just sorry I missed that detail in the beginning ;-;

exotic sand
native root
#

BeautifulSoup

wild thunder
#

no, it's perfectly fine, sorry for bothering

#

and again

#

thank you

exotic sand
#

Did you look at its example bast?

native root
#

Yes

exotic sand
#

Is beautifulsoup capable of doing that?

native root
#

I did not

#

Not builtin, at least

exotic sand
#

Mmm

native root
#

get_text() is similar, but I'm not sure if something exists that does lists and/or alignment

wild thunder
#

hey bast, are you fullstack or do you have a preference?

native root
#

fullstack

wild thunder
#

cool

#

i'm studying html + css to make some relation with python

#

i was trying to study django

#

but it was not making any sense to me

#

the views + urls

#

i was not getting

native root
#

Well, I work with django, so I'm sure I can answer any of your questions related to that :P

#

views + urls are separate concepts/details

#

the asdf/{id for post}/blog-post-title is the route/url--anything that comes in and matches it will be sent to a specific view function, which then does the responding

wild thunder
#

okay

#

it's making more sense now, even why i'm in html, the urls section is "equivalent" to put an "href" in a page?

native root
#

Yes, pretty much

wild thunder
#

<a href=""></a>

#

nice, now i'm making connections

#

hahaha

#

but i'll try to create this little interface, then i go back to djano

#

django*

#

to create a little system

native root
#

good luck!

wild thunder
#

thank you!

#

and hey

#

am i allowed to add you?

#

or comments are closed to the discord group?

#

i see here you have a "helper" tag, then i should respect if you can't

native root
#

I prefer to keep my friends list small, so sorry

#

But I'll be around, and I check this channel fairly often

wild thunder
#

that's ok, i understand

#

anyway, thank you for helping!

#

i'll probably look for your again soon hahah :PPP

proper hinge
#

In Django is doing Q(a=True, b=True) equivalent to Q(a=True) & Q(b=True)?

wild thunder
#

i did not understood this logic

#

newbie alert

native root
#

Yes, iirc it defaults to AND

proper hinge
#

Thanks

#

Is this just not documented anywhere 🙄

#

The documentation on the Q object is fairly poor as far as I can see

native root
#

I had to check the source code ;-;

marsh canyon
#

there is a lot more to it than the docs

#

use dir

#

django docs is not the best at queries

exotic sand
native root
#

Built into bs4, I meant

exotic sand
#

yeah

#

But what is builtin?

native root
#

.get_text(), which lets you specify a tag separator and gives you the page’s text

exotic sand
#

Aha

wild thunder
#

@native root are you there?

#

in the name of each block

#

i put an :hover

#

but this is happening

#

its covering the entire "line"

#

forget it

#

i found the error

#

i put the "box-shadow", the right was text-shadow

native tide
wild thunder
#

i would ask questions, but i cant solve it

#

are you deploying it or developing?

native tide
#

developing

wild thunder
#

check for commas

#

i had a mistake like this

#

was a missing comma

native tide
#

i literally copy/pasted it and it was working on any person's computer, but not mine

wild thunder
#

it's kinda funny

glossy briar
#

Hello guys! I got into Python for automating some of the office jobs I had. I'm liking it more each day and have a new dream now, to be a web developer.

Can someone guide me if I'm doing it right/missing something?

My path is HTML -> CSS -> JS basics -> PHP/Laravel framework AND Python/Django

I already know HTML, CSS and Python to make webscrapers/calculators/small scripts

rigid laurel
#

You can probably skip php/laravel and jump into flask or Django

#

The only real reason to learn php is if you need it for a job

vagrant adder
#

It's better to learn node

#

And do fullstack with js

native tide
#

i'd go with c# it's really popular nowadays

rigid laurel
#

NodeJS+A front end JS framework is a great way to go - thats pretty much the most popular modern web stack

#

Although pure-python for backend web dev, or python+a JS framework is also pretty common (at least I think it is)

native tide
#

Where can I learn web development with Python

rigid laurel
#

Udemy, Django documentation. W3Schools if you don't already know HTML/CSS/JavaScript

#

Flask mega tutorial

#

!resources has a few links

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

vagrant adder
#

corey schafer also has excellent tutorial series on youtube

#

about flask and django

marsh canyon
#

For django go with coding entrepreneurs

solar hatch
#

Any tutorial on HTML and CSS

#

On YouTube

#

Recommendation

ashen trench
#

anyone worked with django rest

quartz lily
#

Hi

#
@font-face {
  font-family: "HKGroteskPro";
  font-weight: 400;
  src: url(".\fonts\HK%20Grotesk%20Pro\HKGroteskPro-Regular.woff2") format("woff2"), url(".\fonts\HK%20Grotesk%20Pro\HKGroteskPro-Regular.woff") format("woff"); }

@font-face {
  font-family: "HKGroteskPro";
  font-weight: 600;
  src: url(".\fonts\HK%20Grotesk%20Pro\HKGroteskPro-Medium.woff2") format("woff2"), url(".\fonts\HK%20Grotesk%20Pro\HKGroteskPro-Medium.woff") format("woff"); }

h1, h2,
#

i have this in my theme.css file

#

this theme.css is in a folder called static

#

and also in the static are my fonts

#
127.0.0.1 - - [20/Dec/2019 12:52:41] "GET /fonts/HK%20Grotesk%20Pro/HKGroteskPro-Medium.woff2 HTTP/1.1" 404 -
127.0.0.1 - - [20/Dec/2019 12:52:41] "GET /fonts/HK%20Grotesk%20Pro/HKGroteskPro-Medium.woff HTTP/1.1" 404 -
#

flask keeps showing a 404

#

when getting these fonts

#

anyone know why this is happening

#

nvm

#

apparently clearing cache fixed it

hollow glacier
#

Is it a good idea to use model methods or whatever they're called with flask-sqlalchemy?

#

(like this)

#
class User(db.Model):
    __tablename__ = 'user'

    user_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    created_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP"))
    updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP"))

    def __init__(self, name):
        self.name = name

    @classmethod
    def create(cls, **kw):
        obj = cls(**kw)
        db.session.add(obj)
        db.session.commit()```
fair wraith
#

I currently have the following code to hold static images: @app.route('/avatars/<path:filename>') def get_avatar(filename): return send_file("static\\img\\" + filename, mimetype='image')
I want to try and add a way for the size to be changeable for example like this: {{ url_for('get_avatar', filename='d.jpg', width=100, height=100) }} So something like /avatars/d.jpg?width=100,height=100 (Example)
Is there any way I can accomplish this? Help is appreciated! Thanks!

vagrant adder
#

@hollow glacier don't do that

#

delete __init__ and create function

#

that init method is already done under the hood

#

and create() way of instancing is not preferred for flask-sqlalchemy

#

just do

user = User()
db.session.add(user)
db.session.commit()
#

if you do print(use.name) you get its name

quartz lily
#

Hey guys im using a bootstrap 4 template

#

and one of my js plugins dont seem to be working at all

#

its a smooth-scroll.js file

#
<a href="#faq" data-toggle="smooth-scroll" data-offset="0">FAQ</a>
#

using it is like that

#

but it wont work at all

#
<script src="{{url_for('static', filename='js/smooth-scroll.js')}}"></script>
#

i made sure to add the script like that

#

and there were no errors in flask when it was loaded

#

it was a 200 request

wild thunder
#

hey guys, anybody knows how to make php based games?

west mulch
#

is API if i make a script with bs4 and requests and gets me back data i want form website?

stark yarrow
#

Hey if I have the following models in Django:

class Client:
    type = "?"
    #...
class Business:
    #...
class Person:
    #...

How do I represent a one-to-one relationship between Client and Business/Person with the foreign key stored in the Client model?

proper hinge
#

create a OneToOneField in the Client

native tide
#

Is Node JS a framework similiar to Django and Flask

stark yarrow
#

A client can only be a Business or a Person.
I want to do something like:

class Client:
    person = OneToOne("Business or Person")
class NaturalPerson:
    # ...
    pass
class PhysicalPerson:
   # ...
    pass

Currently I have something like:

class Client:
    is_natural_person = Boolean()
    is_juridical_person = Boolean()
    def get_person(self):
        if self.is_natural_person:
            return NaturalPerson.objects.get(client=self)
        return JuridicalPerson.objects.get(client=self)
class NaturalPerson:
    client = ForeignKey(Client)
class JuridicalPerson:
    client = ForeignKey(Client)

But it feels like there is a better way to do it.

fair wraith
#

I get this error:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) CHECK constraint failed: user
[SQL: UPDATE user SET grade=?, complete_registeration=? WHERE user.id = ?]
[parameters: ('Junior', 2, 1)]
(Background on this error at: http://sqlalche.me/e/gkpj)

Here is my code idk why it is causing it:

        user.set_complete_registeration(2)
        db.session.add(user)
        db.session.commit()```

Does anyone possibly know how to fix?
native tide
#

@native tide Node is just a JavaScript runtime... Express, a Node JS framework, is what would be similiar to Flask. Django on the other hand is a batteries included web framework which already implements most of the stuff that you could need out of box (authentication etc.).

#

ooh nice. So the website i build with Flask, I can build with Node JS too? replacing Flask with Node JS

#

You can replace a node api with a flask api

#

You could built a react frontend and connect to any of those two

#

I see you're already going with Django, just stick to it, it's great for learning and can built solid products

#

nah i'll stick with Flask

#

thx for the info

native tide
#

wait where did my message go

lone cave
#

@here Has anyone deployed a Django or Flask backend with a React front end app, to production?

native tide
#

@lone cave yes , whats the deal ?

lone cave
#

@native tide Any pain points or things you would have done differently?

native tide
#

@lone cave what do you mean ?

lone cave
#

@native tide as you were developing it, were there any aspects of using those frameworks together, a pain in the ass? If you were to develop another app with those tools, what would you do differently?

native tide
#

@lone cave yes, start from mobile layout first.

cyan wolf
#

yo

#

so

#

wrong channel

native tide
#

Hi everyone

#

I'm new to the python world

#

I'd like to create a rest API, and vue as the front end

#

I'm a bit lost on the options... should I go with Flask or FastAPI ?

#

There seems to be minimal amount of info regarding a rest api with Flask, the first google hit is an article from 2013

#

Coming from the PHP world with Laravel, the python web dev world seems much smaller or difficult to find good resources 🤔

vagrant adder
#

i would say take a look at flask, docs and community forums are great

#

it's extremely easy to piece an api with both of them

#

i have been fiddling with flask about a year now and i can say i am glad i took flask

#

iirc @gleaming herald did some fastapi stuff, i think he can help you out if you get stuck with fastapi

native tide
#

Cool

#

What resources did you use to build a rest api with just flask ?

#

because the flask mega tutorial shows a lot more than just a rest api

#

And isn't very tailored towards making a rest api, more like a backend-heavy app

vagrant adder
#

mega flask is a good tutorial if you are building a corporate website

#

its huge lol

#

i followed corey schafer's flask tutorial series to get to know flask

#

after that it just comes to a lot of googling

native tide
#

The problem with FastAPI is that one guy has like 600 commits and then the others have like 10 commits

#

Same thing with Starlette

#

So I'm like ok.... if that guy isnt interested anymore I acquired all this knowledge for a dead framework

vagrant adder
#

not sure about that

#

also forgot to mention

#

there are 2/3 ways to build a rest api with flask

#
  1. old school way
  • fiddling with a lot of request arguments and if request.method == "POST": stuff
#
  1. flask-restful
    -make models and resources and let the flask-restful do the routing and other heavy lifting
#

3)flask-restless

  • basically cheating but not a lot of customization available
native tide
#

And flask-restplus ?

vagrant adder
#

technically the same thing as restless

#

abstracting your models behind the Resource object

#

same thing done twice

native tide
#

I see

#

Have you played around with JWT auth or oauth2 auth with flask ?

vagrant adder
#

with oauth just a tad

#

jwt is on my bucket list

#

never had to write jwt systems cuz i've been doing just static websites without any particular frontend framework

native tide
#

What about django ?

#

django-rest-framework

#

Community is booming looks like

#

My bad I'm a bit lost with all the options lol

lone cave
#

@native tide Flask is very minimal, you gotta use plugins to get all the features that Django has built in. Flask is a easier to learn and bring up, Django has quite a learning curve. If you're looking for fine control, I would look more into flask, otherwise check out Django.

native tide
#

Thanks for the article

#

@lone cave, it cleared up a couple things for me

#

Do you think this is still a good starting point ?

#

Even if it was written in 2013

#

I just can't wrap my head around the fact that the most comprehensive thing I've found was written in 2013

#

How can python and flask be so popular yet so weird to find info for ?

lone cave
#

@native tide Haha yeah I hear ya. I think people tend to associate web development with JavaScript these days. Python is great for backend though, my team at work has Python running a server-less architecture on AWS (Lambda) right now. Yeah the author of the article you posted (Miguel) is great, he's pretty well known in the Python community.

#

I would take it a step further and use Gunicorn as the web server (super easy to bake in) . Also once you get through some basic projects, check out: https://github.com/zalando/connexion

#

Keep in mind, Python is almost 30 years old, don't worry too much if articles seem a little old. Medium is a good source for technical articles as well.

native tide
#

@lone cave you think people favor node over python ? I'm not a fan of the npm ecosystem

#

The number of dependencies for anything is staggering

#

Though I use Vue on the frontend

#

That I enjoy

#

I want to do a rest api with python as the backend and vue as the frontend

#

Thing is I'm 21 and I wanted to pick a new language, I've been using PHP for a while but a friend told me it could actually hurt my resume to know it lol

#

Because of the negative bias it has

#

I already know Vue

#

So my plan was to learn Python as my backend language, and then Typescript for the javascript side of things

#

Should be pretty set with those skills

lone cave
#

@native tide If you already know JavaScript pretty well, I would just use it for the whole stack (Ex: Node, Vue, Express and whatever DBs). If you're looking to learn a new language and you don't know a statically typed language, check out Golang!

native tide
#

Why dont you recommend python?

#

I know Java

lone cave
#

Ohh okay, cool. Then yeah, can't go wrong with Python!

last light
#

@native tide why Vue?

native tide
#

@last light shipped by default with Laravel and pleasant to work with

#

I'm open to learning react in the future if needed but for now I just want to move on as quickly as possible to Python and Typescript

#

And Vue 3 is coming out soon which will bring support for Typescript

#

In montreal there are quite a few typescript jobs

#

Apart from that

#

The reason I went with Laravel first is cause the tooling is so amazing

#

With Laravel Mix you don't have to learn webpack, you just pass it a couple options and it compiles the libraries you want, with postCSS (minify, remove unused css, etc.)