#web-development

2 messages Β· Page 33 of 1

fathom sapphire
#

all clears

native root
#

hm.

#

try console.log(table_body) inside the loop and trying it

fathom sapphire
#

comes up as this

native root
#

after the call to $(e.target)

fathom sapphire
#

is this the correct location?

native root
#

yes

#

make sure to have a ; though

fathom sapphire
#

still came through as undefine

#

underfined*

native root
#

iiinteresting

#

try logging $(e.target).data()

fathom sapphire
#

is there something im missing?

native root
#

Well, e.target is the event's target

#

$(e.target) is the events target element

#

it seems that it's data is empty

fathom sapphire
#

it made the right amount of {} as the value is though

native root
#

since the data is empty, .table becomes undefined

#

since table is undefined, if(table_body) does not run

#

Since e.target never changes throughout the loop, the if statement never runs

#

and add_row is never called

#

Right, so the loop is working, but the logic to fetch the row to add is not

fathom sapphire
#

so what causes my button with exact same code work?

#

my add row button i want to remove

native root
#

Your #add-row element has a data(), your #travellingwith does not

fathom sapphire
#

πŸ˜„

#

needed to add my data-table

#

gosh that makes me look bad :L

native root
#

no worries :P

fathom sapphire
#

i have 2 rows for selecting partner which is correct

#

and my button disappeared as it;s meant to πŸ™‚

#

but

#

it still doesnt like the consol log

native root
#

?

fathom sapphire
#

or is that logging the table?

native root
#

That's logging the table

#

and means its working

#

You can expand it to look deeper, too

fathom sapphire
#

Blob working πŸ™‚

#

πŸ‘Œ thankyou

native root
#

πŸ‘

gilded dragon
#

Django question.

So, I followed Corey Schafers' Django tutorial on youtube, in which he builds a basic blog. I have completed it and it's ready for deployment, but it's not what I'm looking to build (although I like that I have that app ready to modify and deploy if I want).

There's a tutorial for building a polling website on the official Django docs found here: https://docs.djangoproject.com/en/2.2/intro/tutorial01/
I would like to do both of these projects as different apps within the same overall project, which is currently called webhub.

The reasoning behind that is because my end goal is to have my own website that, when navigated to, forces a login before you can go to ANY page. I plan to be the only one who can access this website, basically. I want it accessible anywhere, but only by me via login. So, the plan is to have it log in, then bring me to a landing page with links to the apps within that landing. Sort of like how google chrome has that default landing page when you first open a tab.

With that in mind, I want to build this polling app from Django and try to tie both apps together, then create a landing that can navigate between them. Is this something that would work, or should I just not do that, and isolate each of these projects, then start work on my whole plan some other time?

#

Sorry, /novel lol...

#

Quick draw-up of what I mean

gilded dragon
#

Anyone?

cursive orchid
#

how do i simply add a script to a button with flask and python
all i need to do is connect a return redirect to a button

vagrant adder
#

<a href="{{ url_for('funcname') }}">

#

And you can style that

hot yarrow
#

is anyone here experienced with flask and would be able to offer me some design advice?

native root
#

Can't try if you don't give any details

hot yarrow
#

ye, sorry just didn't want to spam if no one was available!

native root
#

No worries, feel free to post anytime, it ain't spam

hot yarrow
#

So, I'm making my own flask dashboard, so far it's been smooth but I'm a bit stumped about how to design my configuration page. The python backend also is connected to a gateway class which has a lot of configurations and one of the frontend pages is going to be handling those configuratoins, allowing people to see them and change them

#

What I'm unsure how to approach is how to get/save those values

#

the menus shown there are javascript/css right now

native root
#

Well, first decision is if you want them to save-on-selection a la webapp style, or on a submit event

hot yarrow
#

submit event for sure

#

since those immediately go to the hardware side of things

native root
#

right, and they've got much clearer UX

#

I'd suggest just a regular post request

#

post new settings to a controlling endpoint, and have the endpoint send back a redirect to a "done" page

hot yarrow
#

sweet, ill find a tutorial on that then

#

the url already switches to http://localhost:5000/config#lora1 for each module, would that then just require a app.route('/config#lora1', methods = ['GET', 'POST'])?

native root
#

yes

#

It'd be very similar to a standard form submission, I would think

hot yarrow
#

This’ll make me stress less about deadlines then

native root
#

You can also separate the methods

hot yarrow
#

Thanks!

#

Each with its own route?

native root
#
app.route("/", methods=["GET"])


and 


app.route("/", methods=["POST"])
#

I believe

#

So, ex:

#

@app.route("/config", methods=["GET"])
def config():
    return render_template("config.html")

@app.route("/config", methods=["POST"])
def save_config():
    print(request.form)

hot yarrow
#
@app.route("/config#lora1")
def func():
    print("WOW LORA1?")

I tried to run this as a quick test and it doesn't seem to be reached

#

<a href="#lora1" class="list-group-item" id="lora1" onclick="sidebarfunction(1)">Lora Module 1</a> this is how it's being called

native root
#

Two things there, I think

#

onclick= might suppress the navigation event

#

and an href to a # causes the browser to jump to the element with that as its id/name

hot yarrow
#

even if the url in chrome changes?

#

ah

native root
#

You can change the url in the navbar separately from navigation without using #'s,

hot yarrow
#

wouldnt i need seperate .html files then?

native root
#

Not necessarily

#

window.history.replaceState() is a non-loading navigation event, but more importantly, the html files returned by flask are specified by you

#

Say you're on /config#laura1, and you have the following html:

#
<form action="/config-submit/laura1">
    <input>
    <input>
    <input type="submit" value="Save Changes">
</form>
#

Clicking the "save changes" button will trigger a POST request to /config-submit/laura1

#

if you name your route "/config-submit/<config_name>", and take in config_name

#

then the last element of the url is passed into your function

#

Your function could then return a redirect back to /config#laura1, for example, to go back to the original page

#

However, considering that you've already got javascript hooked up

#

an ajax request to /config-submit with the relevant parameters might just be simpler

hot yarrow
#

ah

native root
#

Here's a simple jquery example:

#
$.post( "/save-config", { name: "Bast", time: "2pm" } );
#

The flask side, request.form['name'] would be "Bast"

hot yarrow
#

I just threw that in

#
@app.route("/save-config", methods=["POST"])
def prase_request():
    print(request.json)
#

get a name error for request, undefined

#

oh im missing a import, my bad

#

that did the trick

native root
#

πŸ‘

hot yarrow
#

Hey @native root, took a break and got back onto it, right now I'm trying this:

@app.route("/get-config", methods=["POST"])
def return_config():
    return_value = None
    if request.form['module'] == "lora1":
        return_value = {
            "tx_power": 23,
            "bandwidth": 100
        }

    return_value = make_response(jsonify(return_value), 200)
    return return_value

and on the javascript side I got:
var lora_stuff = $.post( "/get-config", {module: "lora1"} );

#

when I look at lora_stuff, I get [Object object], tried json.parse() but that didn't help either

native root
#

lora_stuff.tx_power ought to be 23, there

hot yarrow
#

tried that in the console

native root
#

Hm.

#

oh

hot yarrow
#

ohhh!

#

console gave me a hint it's

#

lora_stuff.responseJSON

#

{bandwidth: 100, tx_power: 23}

#

πŸ˜„ thank you!

native root
#
$.post( "/get-config", {module: "lora1"}, function(data) {
    console.log(data);
}, "json" );
hot yarrow
#

oh you can just throw a function in there damn

#

i havent used jquery much before

native root
#

but glad its working

azure plume
#

I'm trying to communicate between python webserver with websockets using the sockets library
but when I try to connect it to my javascript client using websockets, the connection fails
this is part of my code
the client:

Display.innerText = Address
        var socket = new WebSocket(`ws://${Address}`)
        socket.onmessage = function(event){
            //This is called per message
            //Message = event.data
            document.getElementById("textarea").append (event.data + "\n")
            return false;
        }
        socket.onopen = function(event){
            //alert("Connected to server.")
        } 
        function sendMessage(message){
            socket.send(message)
        }

the server:

server = open_socket()
        while True:
            sock, addr = server.accept()
            thread = threading.Thread(target=client_thread, args=(sock,), daemon=True)
            thread.start()

can anyone help me?

native tide
#

hi guys

#

i'm using django 2.2.3

#
news
β”œβ”€β”€ __init__.py
β”œβ”€β”€ __pycache__
β”œβ”€β”€ admin.py
β”œβ”€β”€ api
β”œβ”€β”€ apps.py
β”œβ”€β”€ fetcherHelper.py
β”œβ”€β”€ management
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ __pycache__
β”‚Β Β  β”‚Β Β  └── __init__.cpython-37.pyc
β”‚Β Β  └── commands
β”‚Β Β      β”œβ”€β”€ __init__.py
β”‚Β Β      β”œβ”€β”€ __pycache__
β”‚Β Β      β”œβ”€β”€ create_news.py
β”‚Β Β      β”œβ”€β”€ feed.py
β”‚Β Β      └── get_main_feeds.py
β”œβ”€β”€ migrations
β”œβ”€β”€ models.py```
#

currently i'm working from get_main_feeds.py

#

i tried
from news.models import News

#

it didn't work

#

this is my os.sys.path

#

@native tide from .... import News ?

#

ValueError: attempted relative import beyond top-level package

#

yeah

#

i can do that

#

but i was wondering if there was a bettere solution

native root
#

I would expect from news.models import News to function

#

Is news missing from INSTALLED_APPS?

native tide
#

nope

native root
#

How are you calling it?

#

python manage.py command?

native tide
#

so i'm trying to create a custom django command which calls a class in the same dir which calls news.models import the model to add data to db

native root
#

is there a bare news?

native tide
#
β”œβ”€β”€ Scripts
β”œβ”€β”€ django_project
β”œβ”€β”€ domain_monitor
β”œβ”€β”€ media
β”œβ”€β”€ news
β”œβ”€β”€ seed_data
β”œβ”€β”€ static
β”œβ”€β”€ todolist
└── users
#

these are all the apps that i have

native root
#

How are you running the command

native tide
#

hmn with ctrl+alt+n in vs-code

#

maybe it's the problem

#

the fact it that that create_news should be indipendent from django shell

native root
#

yes

#

That is the problem

#

django sets up its installed_apps imports when you call the django manage.py commands

#

This allows you to easily import and access other modules

#

if you simply run the script separately, the namespace is not initialized, and you get errors like the one you were experiencing

#

If you wish to have access to your django models, then it's pretty much given that your command should be run through the django commands interface

#

Here is a relevant guide, if it's not what you're doing

#

They are callable via python manage.py custom_command_name for custom_command_name.py

dense hound
#

Hi, anyone ever converted a Flask application to exe? It's possible but I'm getting an error File "app\__init__.py", line 2, in <module> from flask_socketio import SocketIO ModuleNotFoundError: No module named 'flask_socketio' [9608] Failed to execute script app I've googled but I Can't find a solution, when I do pip3 freeze in my venv I'll get the following: Click==7.0 Flask==1.1.1 Flask-SocketIO==4.2.1 gunicorn==19.9.0 itsdangerous==1.1.0 Jinja2==2.10.3 MarkupSafe==1.1.1 python-engineio==3.9.3 python-socketio==4.3.1 six==1.12.0 Werkzeug==0.16.0 It looks like flask-socketio is installed... Anyone got an idea?

vagrant adder
#

Did you activate venv?

slender hamlet
#

Can anybody tell me why I should learn web development (html, css, javascript...) when there are now websites that can make it for you?

bright vector
#

Someone has to make those websites. And fix all the broken websites those websites make. Go to fiver and search for "wordpress" if webdev was as simple a using a wysiwyg website there would be no need for all those wordpress devs.

rare lagoon
#

Which is the best language for starting to learn about web develolment?

bronze apex
#

Hi. Anyone with HTML experience who might be able to help be troubleshoot my code?

graceful summit
#

I want to create a website where people can watch ads that gives me money and i give them something as return
But I don't know how to put ads
using django

unborn terrace
#

@graceful summit use your ad provider's API

graceful summit
#

@unborn terrace sorry what does this mean

unborn terrace
#

@graceful summit ad providers have an API, i.e. a set of interactions you can do with them from your code, for instance retrieving an ad to display it, information about these interactions and how to do them is available in documentation they provide

graceful summit
#

Django documents?

unborn terrace
#

No

#

Ad provider's

graceful summit
#

What is the best one
Google adsense?
Or what

unborn terrace
#

I don't know, look them up

graceful summit
#

Okay thanks bro

dense hound
#

@balmy forge Yes I did

balmy forge
#

I think you pinged the wrong person? xd

dense hound
#

oh lol sorry haha

#

@vagrant adder Yes I did

honest flame
#

Hey folks, I want 2 ask if there's any way how do you enable google maps api

frigid egret
#

@honest flame You'll have to specify the question. Google has documentation on their APIs

#

Hi all

#

I have a problem with my website, it's on Django.

#

Core of the problem is that I have no clue how to debug this particular bug.

#

When I'm sending forms on the website, it works fine, there's validation that also tells me everything is fine.

#

If I fill a form from my main PC, I can see new objects in admin panel.

#

But doing the same thing from a new IP (my phone for example) doesn't show me any errors, yet objects don't appear in admin panel.

honest flame
#

Yeah

dense hound
#

I managed to fix the issue where it would display the error File "app\__init__.py", line 2, in <module> from flask_socketio import SocketIO ModuleNotFoundError: No module named 'flask_socketio' [9608] Failed to execute script app But now when I run the exe it won't return anything. Added some print files in the main file but it won't even print those when I run the exe

#

anyone has an Idea? Using pyinstaller for my flask application. Thanks in advance python !

dense hound
#

Fixed it.

bright vector
#

How?

oak bone
#

Hello All, I am new here. And I an new to learning Python as well.
Currently I am trying to learn it through a small project where I am connecting to my IBM i server and showcasing some data in the chart forms..
I am using python and Dash by plotly as the dash-boarding framework.
I wanted to connect to some who has experience in building dashboard using Dash framework.
Thanks in advance 😊

rare oar
#

guys I'm dying here I don't know the flow
I created a pycharm project with django and docker. Used postgres
if I run anything on the container it works
but if I try to use local manage.py or django console, I get an error
django.db.utils.OperationalError: could not translate host name "db" to address: Unknown host
I'm assuming this is because in my django DATABASE setting I put 'db' as the HOST
If I change it to localhost, it'll work in manage.py locally
but then break on the container
?!

tired root
#

How do I output an error in Flask, so that Apache picks it up and throws it into the apache error log?

#

just write it to std::err?

native root
#

I believe you would need to return an error status code

tired root
#

Thanks. Do you know which one is suitable so that Apache still serves the content, but logs the error?

#

and how do I pass the message?

native root
#

I mixed two things up. If you want your stacktrace to appear in the apache error log, then printing to sys.stderr should suffice

#

If you want apache to log an erroring page without displaying "Recovery" content--like on a 404, for example, you'd want to return the template with the appropriate status code

#

You can do that in a flask route via return template_rendered, status_code

tired root
#

I tried to raise an exception, Apache shows a 500, but the log is empty. I am going to try to write std err

native root
tired root
#

Printing to stderr does not work. Error Handlers are just custom error pages, aren't they? Apparently getting apache to pick up your output is harder than anticipated.

#

I am stupid, printing to stderr does work. Was looking in the wrong log πŸ˜„

#

forgot that I had 2 separate logs for frontend and backend vhost

#
@admin_app.route('/myerr')
def testerror():
    print("Custom Error", file=sys.stderr)
    return "Hello World"

Output:

root@host1:/var/log/apache2 # cat admin.error.log
[Fri Oct 18 06:17:36.115208 2019] [wsgi:error] [pid 8367] [client 10.10.10.1:49505] Custom Error
native root
#

I was about to mention it :P

#

Generally practice is to return a "Internal Server Error", 500

#

5xx error codes indicate that the server had an error, and is useful for callers to get

#

But it's up to you and your needs honestly

tired root
#

Unless you want the app to continue operations. I want to silently log the error but keep going

native root
#

Right

tired root
#

it's not critical

native root
#

Then yeah, you're good

tired root
#

Thanks Bast πŸ™‚

native root
#

Of course

vagrant adder
#

@rare oar
That happens because it cannot find the database since it's in your container that is shut down

rare oar
#

the container is running

#

its like it doesn't transfer to my local host

#

To fix I set a environment variable POSTGRES_HOST in the container

#

and in my code did something like:

#
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'zclpassword',
        'HOST': os.environ.get('POSTGRES_HOST') or 'localhost', 
        'PORT': 5432 # default postgres port
    }
}
#

That cannot be right haha

native root
#

Generally you use a local_settings.py file

#

Which is only present in your development environment, and is imported at the end of settings.py (which should have been done for you). This would allow you to override the DATABASES setting with the localhost one

rare oar
#

ok I will go for that. I guess then just in the Docker I have to make sure to not COPY that over

native root
#

yep

ashen anchor
#

Hey guys, I have a quote model and I want to create a foreign key link to one of many different product type models. Is there a recommended way to achieve this? One idea I had was to create a base Product model, then have one to one links from instances of these to the various different product model instances. Finally linking my quote model instances to the parent Product model instances. I look forward to any thoughts or insight, it would be much appreciated

native root
#

Are you using an orm?

#

What you're saying there is usually the way it's done, as far as I know

ashen anchor
#

Sorry, missed out completely that I'm using Django

dense hound
#

Hi guys!
I'm currently trying to convert my Flask application to an executable file.
When I run the normal .py file it works, but when I run the exe I get the following error:

Traceback (most recent call last):
  File "testfile.py", line 4, in <module>
  File "app\__init__.py", line 14, in create_app
  File "site-packages\flask_socketio\__init__.py", line 245, in init_app
  File "site-packages\socketio\server.py", line 108, in __init__
  File "site-packages\engineio\server.py", line 130, in __init__
ValueError: Invalid async_mode specified
[13920] Failed to execute script testfile

I've google around but could not find anything helpful.
Maybe it's something with hidden imports?
Thanks In advance python !

#

this is my init.py

#
from flask_socketio import SocketIO

socketio = SocketIO()
def create_app(debug=False):
    """Create an application."""
    app = Flask(__name__)
    app.debug = debug
    app.config['SECRET_KEY'] = 'XXXXXXXXXXXX'
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
    socketio.init_app(app)
    return app
#

This is where the errr occurs (line 14) ```socketio.init_app(app)

native root
#

@ashen anchor Django supports model inheritance

#

class MyModel(models.Model):
    some_shared_fields

class MyOtherModel(MyModel):
    some_unique_fields

#

MyOtherModel.my_model would give the parent class instance

unborn terrace
#

@native root why would inheritance be needed here ?

native root
#

Gatt was describing a situation involving inheritance, as far as I could tell, with multiple model types that are all kinds of another model

#

Eg, a set of "products" specific to different vendors

#

each linking back to a parent "shared product" model

unborn terrace
#

@ashen anchor why would you need inheritance as well ? πŸ€”

native root
unborn terrace
#

@native root if I understand correctly, these β€œproducts” would be prone to be dynamically created. Hence not suitable to model inheritance. More like having VendorProduct objects linked (by foreign key for instance) to a Product object

dense hound
#

@native root yeah I'm reading trough it atm but don't think it will help me out

#

such an annoying error

native root
#

Why do you not think so, its your exact problem?

ashen anchor
#

Yeah, essentially the product types are very different but a known quantity so I've opted to create different models for each product type

#

The quote model however just needs to contain costs/prices per unit (among other things)

#

But I need it to link to a specific product instance, but obviously there's different product types so a standard foreign key won't work and it seems GenericForeignKeys aren't recommended

native root
#

Inheritance is exactly what you need

unborn terrace
#

@ashen anchor why make your different product types different models ?

ashen anchor
#

Because each product type has completely different attributes/methods attached to them

unborn terrace
#

How many different types do you have to work with ?

ashen anchor
#

Around 6

native root
#
class Quote:
    product = ForeignKey(Product)

class Product:
    stuff

class BobsProduct(Product):
    stuff
#

BobsProduct.product gets you the product

#

and you can reverse it as well to go from quotes to individual vendors

ashen anchor
#

@native root makes sense to me, what is happening in the background whilst doing this?

#

Is it essentially the onetoone link I was planning?

native root
#

Django sets up a foreign key from BobsProduct to Product, and uses that when it loads BobsProduct for all the inherited fields as well

#

Yep

ashen anchor
#

Excellent, any downsides I need to be concerned with?

#

Aside from the performance hit with joins (which won't be a concern in this case)

native root
#

There's some interesting inheritance details with the metaclass, but if you specify everything normally it ought to simply make sense

ashen anchor
#

Perfect, really appreciate your help

native root
#

good luck

ashen anchor
#

Thanks πŸ˜„

dense hound
#

@native root apparently it worked to import ```from engineio.async_drivers import threading
import engineio
import socketio
import flask_socketio
import threading
import time
import queue

native root
#

yep, πŸ‘

#

pyinstaller goes and looks in all your files for imports to know what to include, but since engineio doesn't have a normal import threading inside it, it's missed and not included by default

tough star
#

I'm making a dynamic text boxes form: https://paste.pydis.com/ufikiqihay
How I can give for each text box, a dynamic number and, when I click on the plus button, add the new text box directly under the first main text box?

vagrant adder
#

In jQuery i think there is .append()

#

This should help

still talon
#

Hi, this is not strictly python related but is still very conceptual, so I feel like your input will be valid.

Hi, for my senior design project my team is going to be implementing a webapp that uses a kahoot.it - like room system to group users into a session together by a code, but I had some questions on technologies for implementing this.

We will have access to a webserver and webhost, and our backend will be Rails. What technologies or libraries can I look into for implementing this type of system. Right now, I am imagining running one application on the domain that handles all users up until the point they enter a code or create a room, at which point docker will spin up an instance of a different application to handle the rest of the app. All other users with the same code will be routed to this instance.

Note: I have not used docker, and am mostly wondering if this is overkill and there is a simpler application or technology that can handle this sort of room or session-based connection grouping?

native root
#

@still talon That's heavily overkill, you can easily manage messages from multiple users within a single execution context. Those apps often work via socket.io, which has a rooms system that you might want to look at

still talon
#

Thanks, is there a name for this sort of technology? Just don't know what keywords to use for research (beyond socket.io now)

#

Looks like messaging, maybe?

native root
#

I'm not sure. I know Websockets, and general chat howtos are quite helpful for this, at least for me. https://flask-socketio.readthedocs.io/en/latest/ is a good prototyping framework for python, for this, and might serve as a source for keyword fodder

still talon
#

Thanks!

dense slate
#

I have a user model that has a ManyToMany for "DayOfWeek" where you choose any one or more of the days of the week.

When I query the DB against other users, how can I display any users that match? Like, all the users that match Monday, or Monday and Tuesday, etc.

#

If it's just one value, I can handle it, but what do you do in the case of multiple values?

keen sphinx
#

is there any proper, short way in Flask to add an argument to use in Jinja2 templates during a request, for every path?

tired root
#
@app.context_processor
def process_context():
    return dict(mode="Development")
#

example

#

mode would be injected into every template

#

@keen sphinx

keen sphinx
#

thanks

graceful canopy
#

so I'm building a websocket server

#

but when a user logs in, should a client send the raw password for the server to encrypt it and search the database for a match?

keen sphinx
#

you mean in plain text?

#

if you're using HTTPS it should be enough

#

the server should just do the hashing part

tired root
#

HTTPS is a silver bullet

#

it is not unimpenetrable

#

hash the password client side before sending, apply salt and pepper on the server

#

@graceful canopy

graceful canopy
#

Is there any examples I can see?

#

I’d appreciate them

#

And yes @keen sphinx

tired root
graceful canopy
#

Nice but how would the server check for matches in the database?

tired root
#

It is the same

#

digest with sha256, send, apply salt and pepper, check

#

make sure the base numbers stay the same and you will always get the same result

graceful canopy
#

Okay thanks I’ll look into it tomorrow

keen sphinx
#

an extra layer of security, I guess

#

but that wouldn't help if someone took control in the middle of the HTTPS connection, wouldn't it

tired root
#

yes it does

keen sphinx
#

never heard of it before, do you have some paper or video about it?

#

so I can understand what it does in-depth

#

is this basically browser-specific?

tired root
#

What you mean?

#

the underlying algorithms are all the same

keen sphinx
#

not among browsers*, I worded it poorly

#

but in the browser

tired root
#

all new browsers support it, if that is what you are asking

keen sphinx
#

I guess I did understood but didn't find it that useful

#

but that wouldn't help if someone took control in the middle of the HTTPS connection, wouldn't it
this still doesn't click to me, if I'm the bad guy I can just tell the client to not encrypt the password at all

#

it's only useful if something happens to the server itself

#

(which I admit is not a totally pointless idea, but for most cases it wouldn't do much)

hot yarrow
#

Hi, I'm using flask and have a few design questions.
So I have a mongodb database which has a list of devices and information recieved from those devices. If I want the first webpage to show a list of those devices, and then when the user selects one, it takes them to another page which is customized to show a certain type of graph there, how would you implement this? '~'

vagrant adder
#
@app.route("/all")
def all_devices():
    devices = Devices.query.all()
    return render_template("all.html", devices=devices)
#

and below that make a route with id parameter in url

#

and query by url

elder nebula
#

Do you know any good Rich Text Editors for the Django? CKeditor is good, but when I asked about the license they said, that for order us to help you, you must first puchase the commercial lisence.

native root
#

There is TinyMCE, which is available under the LGPL, and CKEditor 4, which is available under GPL3, LGPL, or MPL, or commercial, and CKeditor 5, which is available under GLP3 and commercial

#

I suspect there's a few others that I'm not familiar with

#

LGPL permits commercial usage

elder nebula
#

LGPL, is that where the code must be made public?

native root
#

no

#

GPL is where code must be made public

#

LGPL is where your modifications of the lgpl code must be made public

elder nebula
#

When I use pip install django-ckeditor, which one am I using Ck 4 or Ck 5?

native root
#

CK4

elder nebula
#

Where can I check that?

native root
#

This version also includes:

support to django-storages (works with S3)
updated ckeditor to version 4.9
elder nebula
#

I can't use the lastest version of the CKeditor, I need to put in the requirements django-ckeditor 4.9.0 or something. Right?

#

The lastest version of ckeditor is 5.7.1 So I can't use that one under the LGPL

native root
#

django ckeditor is the python package that adapts ckeditor 4.9, automatically including it within django-ckeditor 5.7.1

#

CKEditor 5 does not have a stable, clearly installable django package at this moment

#

This is due to it's large changes: removal of LGPL, and a distancing from the html backend

elder nebula
#

Hmm... So If I modify the source code of ckeditor then it must be made public?

native root
#

there is detail, and I am not well versed enough in the license to say

#

but I believe so

elder nebula
#

Thank you

dawn drift
#

I'm looking for a good intermediate-level Web site project that requires HTML, CSS, JavaScript, Python and MySQL. Preferably with the ultimate solution to help me through. Purely to learn. No more shopping carts. πŸ™‚

native tide
#

@dawn drift you can always make a stripped down version of something like facebook, for instance only having functionality for a feature like status posts/comments, or chat

#

something that implements elements of the page dynamically changing

dawn drift
#

@native tide Thanks!

vapid steeple
#

make your own framework

pliant hound
#

Anyone here have experience using flask-ckeditor?

supple loom
#

Hey, i am working on Restplus APIs with flask.......my login endpoint is working fine but on logging out .....the auth_token is getting no data
the code for logout API is this :

def logout_user(data):
        if data:
            auth_token = data.split(" ")[1]
        else:
            auth_token = ''
        if auth_token:
            resp = Enduser.decode_auth_token(auth_token)
            if not isinstance(resp, str):
                # mark the token as blacklisted
                return save_token(token=auth_token)
            else:
                response_object = {
                    'status': 'fail',
                    'message': resp
                }
                return response_object, 401
        else:
            response_object = {
                'status': 'fail',
                'message': 'Provide a valid auth token.'
            }
            return response_object, 403
#

on logging out it says provide a valid auth token

supple loom
#
def login_user(data):
        try:
            # fetch the user data
            user = Enduser.query.filter_by(email=data.get('email')).first()
            if user and user.check_password(data.get('password')):
                auth_token = user.encode_auth_token(user.id)
                if auth_token:
                    response_object = {
                        'status': 'success',
                        'message': 'Successfully logged in.',
                        'Authorization': auth_token.decode()
                    }
                    return response_object, 200
            else:
                response_object = {
                    'status': 'fail',
                    'message': 'email or password does not match.'
                }
                return response_object, 401

        except Exception as e:
            print(e)
            response_object = {
                'status': 'fail',
                'message': 'Try again'
            }
            return response_object, 500

and this is login

vagrant adder
#

where are you getting this data from

#

i'm guessing your frontend part of the app

#

it could be that on your logout part your frontend/whatever is giving wrong data

#

or somehow parsing it wrong

frigid egret
#

Hi all

#

Can I request a code review please? Trying to work out Django Rest + React. I'm learning Python with my friend learning React.

#

Seems like I've done my part (Django Rest) correctly, and he gets code 200 on his end, he can't properly handle the data I'm sending.

#

So I would like to make sure that I am actually doing everything right on my side.

#

The program itself is very simple, only 1 application with 2 models.

#

If anyone is willing to review my code, I'll share it in pm, since it also contains the way to access my local database.

supple loom
#

@vagrant adder There is no frontend part i am working only on backend...i will share the controller file code..

@api.route('/userlogin')
class UserLogin(Resource):
    """
        User Login Resource
    """
    @api.doc('user login')
    @api.expect(user_auth, validate=True)
    def post(self):
        # get the post data
        
        post_data = request.json
        return UserAuth.login_user(data=post_data)


@api.route('/userlogout')
class LogoutAPI(Resource):
    """
    Logout Resource
    """
    @api.doc('logout a user')
    def post(self):
        # get auth token
        
        auth_header = request.headers.get('Authorisation')
        return UserAuth.logout_user(data=auth_header)
supple loom
#

Hey, what is a good site to read about workflow in flask?

vagrant star
#

Django:

#

template does not load views when the same template is called from other template django

#

what should I do?

supple loom
#

@pliant hound i need to know about workflow only.....i have created my endpoints and now i want to learn how to line them up one behind the other.

pliant hound
#

Okay

primal drift
#

hye, wondering how do I return database that I want, for example name he will return table 1 and she will return table 2 ... right now when i give she it will return both table 1 and 2

#

even if I give he it will give all the database that already stored

#

so idk how to say it, but how do I iterate for each name will return their own table

cursive orchid
#

i have a bootstrap form
to collect a user input for a webhook
then use that input to plug it in for
hook = Webhook(INPUTTED WEBHOOK HERE)
how would i do that

#
<form>
      <div class="form-group">
        <label for="get_webhook">Enter Webhook</label>
        <input type="text" class='form-control' id='get_webhook' placeholder="Enter a Webhook">

      </div>
    </form
supple loom
dull rock
supple loom
#

i found them a little hard πŸ˜…

#

or maybe it wasn't what i am looking for

#

what should i use for front end development for my API constructed with flask-restplus...any suggestions?

quiet kite
#

Hi. Does anyone have experience with the development of a multi tenant platform with Django ?

vagrant adder
#

take a look at blueprints @supple loom

#

they are usually used to organize app a little bit

#

and for the frontend, you might take a look at vue or react, depends on what your website would do

supple loom
#

@vagrant adder i am sorry but blueprints for which problem ?

vagrant adder
#

You asked about a workflow in flask apps

pliant hound
#

Anyone know why I wouldn't be able to call init_app() on a flask extension?

#
scss = Scss()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)
    scss.init_app(app)

    return app
``` Doesn't work
#

Sorry- Scss() comes from the flask-scss package

#

I keep getting the error:

    scss = Scss()
TypeError: __init__() missing 1 required positional argument: 'app'
vagrant adder
#

Take a look at docs, i think you need to specify the flask app as the argument

#

Never worked with scss but that is my assumption

pliant hound
#

Yeah, it was working before I tried throwing it in a factory function 😦

#

Not sure what the fix is now, though

vagrant adder
#

Well, you should look if scss supports factory style

#

It doesn't look like it supports factory

pliant hound
#

Yeah the docs say no dice

#

It also hasn’t been worked on since 2015 haha

vagrant adder
#

Hahahahah

#

Good luck

last basalt
#

Hey guys, is anyone familiar with django-scheduler or something similar? I need to make an sscheduling calendar web app in Django, but im stuck. I searched every whole, and it seems that they are lack of documantation for that. JS has "fullcalendar", and im wondering is there something similar for django? (That actually works)

last basalt
#

no one? @sturdy sapphire

supple loom
#

okay @vagrant adder

#

can anyone tell me what is the problem in my implementation of token based authorization ? .....coz i am stuck at logout ...logout function is ok but the problem is in token

quiet kite
#

Hi, anyone here uses django with tailwindcss ?

gilded dragon
#

DJANGO:

What is a good book or web resource I can move into after finishing the Django Documentation tutorial series website, something that's not completely 100% beginner? I have a PDF for Two Scoops of Django but it still seems a bit advanced for me, and I'd like to bridge that gap with a different resource. Does anyone have any suggestions?

vagrant adder
#

O'rilley books

supple loom
#

if i need to pass two arguments in my get request .....what is the correct way to do that ?

#

@vagrant adder

#

in controller file..where we define routes

vagrant adder
#

what

#

i'm a bit busy now

supple loom
#

tell me later then

vagrant adder
#

you got your code on github?

supple loom
#

well i have but it's private repo

#

i can share on pydis

vagrant adder
#

sure

supple loom
#

the first part is route

#

second is function

#

idk how to pass two variables in get function

gilded dragon
#

@vagrant adder Can you give me some examples, or at least the author's full name?

supple loom
#

changed a bit

#

"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. You have requested this URI [/movie/movieLanguage/x-men/english] but did you mean /movie/movieLanguage/<title>/<language> ?"

the error message i am getting

vagrant adder
#

i think you put wrong string in your .route()

native tide
#

hi on instagram.com i am trying to scrape user profile data automatically however for the instagram highlights cover, how can i scrape these in their original size? i can only seem to get the size shown on page?

vagrant adder
#

@native tide i think that's against ig's tos

#
Rules
5. We will not help you with anything that might break a law or the terms of service of any other community, site, service, or otherwise - No piracy, brute-forcing, captcha circumvention, sneaker bots, or anything else of that nature.
native tide
#

oh i didn't know

#

my bad

vagrant adder
#

we cool πŸ‘Œ

native tide
#

are you allowed to tell if its its possible though lmao

#

because it would save me a lot of time

vagrant adder
#

i'm not allowed, staff here is really strict about it

#

i can say you can most certainly acomplish what you want but i'm not allowed to help since it's illegal

native tide
#

oke then i am assuming its not possible πŸ™‚ il just go further on without it i suppose

vagrant adder
#

πŸ‘

native tide
#

why illegal bw? i am not a lawyer?

vagrant adder
#

going against site's tos is illegal

#

if they say automatization and crawling is forbidden, then it's not really the wisest idea to go against tos

native tide
#

oh i thought "if i can see it, i can use it"

#

it was just only a small project to enhance my data analitics rather

supple loom
#

@vagrant adder i think you put wrong string in your .route()

yes that's what i think too....but idk how else to pass two variables to it

vagrant adder
#

you did it partially correct

#

take a look at article i sent

#

you are not defining types of your parameters

magic prism
#

CAn i get some help with Flask here?

native tide
#

yes, just say what your problem is

magic prism
#

I wanna do something where you open a link and then it loops a string

#

Is it possible?

#

I attempted in 3rd route but failed...im assuming you need to return cause its a function

#

But can you return a loop of strings??

native tide
#

not exactly

#

you can't have the server return an infinite amount of stuff

magic prism
#

Ahh

#

Damn

#

Thats too bad

native tide
#

but you could make it return some javascript that generates all of it

magic prism
#

I havent gotten to javascript yet

#

So without JS its impossible?

native tide
#

yes

#

you could return it a lot of times, but you can't return an infinite loop without javascript

vague seal
#

Does anyone have a working example of a .well-known/acme-challenge/ using Django in 2019 and Python3??

#

For ACME v2*

digital depot
#

hey, i've been trying to setup a website run by flask, and i was wondering how i'd be able to make it publicly available

#

i know of stuff like localtunnel and ngrok, but ngrok has caps on the amount of users that can be on the site at once and localtunnel is extremely inconsistent (it goes down often)

#

i've considered setting up my own localtunnel server that runs on the same VPS that my flask site would be running on in order to make it public but there's no documentation or tutorials and the stuff that's available is just hard for me to understand since i'm a novice at all of this web development stuff

#

if anyone could help me out, i'd really appreciate it. just ping me so that i don't miss your message πŸ™‚

vague seal
#

Do you mean public that you can asscess externally or public to the entire web @digital depot

digital depot
#

public to the entire web

#

my bad, should've made that clearer

#

@vague seal

vague seal
#

on your host makesure the ports are open (80 or 443)

#

then pick and setup a webserver for flask (nginx or apache or ...)

#

then set your domain's A tag to the servers IP address

#

if you just open the ports you should be able to access the flask site as is going to the browser and typing in the ip address

digital depot
#

i tried using the 5000 port and idk if i've been doing it wrong but it wasn't working

#

i'm using a windows VPS and i just added a windows firewall inbound rule with the specific port and it wasn't working

#

i'll try again using the 80 port

digital depot
#

it didn't work, so i'm going to try using nginx instead

digital depot
#

@vague seal do you have a guide for setting up nginx that you'd recommend? just wondering because for a beginner, a lot of the guides i'm looking at are a little bit tough

vagrant star
#

I have search bar inside admin/app/model . How do I get "GET" the search result. Well the url for the the search result is in the form of admin/app/model/?q=type and I have to put the url pattern : admin/app/model before admin/ which conficts with the model page itself. I just want the search result(query)>.

soft chasm
#

hey i've a dumb question about flask: if in enable the adhoc auth, i understand it's whack and not ideal because of the certificate changing issue, but will it at least encrypt stuff end to end? what i want to do is just build a secure login page for internal use where i know i can do get/post requests for the login stuff which isn't being sent in plain text

gentle lark
#

is there a flask community discord or irc that you know of?

vagrant adder
#

There is

#

Both irc and discord

#

@digital depot
One question

#

Do you want to self host it or by someone else

digital depot
#

@vagrant adder i ended up figuring it out, but i'm self hosting it

gentle lark
#

is it on freenode?

#

also what is it called on irc

#

and can you link the discord one as well

#

thank you

#

much appreciate it

vagrant adder
#

1st paragraph

gentle lark
#

saki i love you

vagrant adder
#

#nohomo

native tide
#

in django how would you get a field that lists all fonts

#

eg. a post model, and one of the fields is a field where the user can select a font for the post

#

i'm thinking of using tkFont

#

πŸ€”

gentle lark
#

i would for loop through all the fonts i want to show taken from the context in the view and then put an id on each font when rendering

#

then grab the id from the backend

native tide
#

hmm i don't think i would put an id on each font

#

since you can just use the font name itself

#

eg. <font face={{ post.font_name }} color="green">This is some text!</font>

#

in template

gentle lark
#

you basically need to show all the fonts that user wants and then see which ones they wanted in the backend

#

so for loop to show all of them on template and then grab them by value or id or anything you want from the backend

#

as long as you know what they wanted in the backedn youre set

#

would you say that a flask project more secure than nodejs express project by default?

native tide
#

i don't know much about nodejs

#

how are you supposed to create a for loop, that iterates through the fonts and also lists them in the dropdown menu?

#

i want it to be a field

#

font = models.OnetoOne(fonts, other_fields)

gentle lark
#
def fontview(request):
    return render(request, template, context=font)

#template

{% for font in fonts %}
    <div id="font"> font </div>
{% endfor %}
#

something like that

#

@native tide

native tide
#

πŸ€”

#

ok

gentle lark
#

do you get what i mean?

native tide
#

yeah

#

but when the user creates a post i want them to have the option to select the font of the post via a drop down menu

#

and when it displays the post (in _post.html, the html file for a post) it will display the font the user also chose

gentle lark
#
{% for font in fonts %}
     <select>
          <option value="font">font</option>
          <option value="font">font</option>
          <option value="font">font</option>
          <option value="font">font</option>
    </select> 
% endfor %}

#

thats html not python anymore

native tide
#

ok

#

i'll try when i get the chance

gentle lark
#

@native tide you got this boddy!

native tide
#

πŸ˜„

vagrant star
#

Hey I got the result after clicking on search bar in admin but I want to use this query set in diff views. How to do that??

#

Django.

last lily
#

Hey! I want to make a website with a user login system where users can add / remove / modify / lookup from a database. Is Django/Flask or other python stuff suitable? I want something really simple, I have a bit of experience with python but not web dev. Should i learn pythonic web dev or is there some other platform that fits better for my needs?

vagrant adder
#

if you want something really simple and easy to work with, take a look at flask

#

corey schafer has a great series on yt

supple loom
#

hey saki i am getting conflict in one function what could be the reason?

#

it worked

#
{
  "title": "string",
  "released_on": "2019-10-24T15:57:11.093Z",
  "hindi": true,
  "english": true,
}
#

this is my dto(as it shows in swagger UI).....this true value shows here is saved as false in DB also false is saved as same (means these values is not getting accepted )....and false is the default value(in my model).....capitalizing T and F gave me error....what to do?

#

i took a way around

#

what happens when the authorization token expires?

sudden bramble
#

Hello!
I was wondering if I could get some input on this.
I've got an API and a Worker that I've just configured with Docker compose to run separately.
The issue I'm having is that when they run locally on my machine there is no problem using Django's file storage and the default_storage class to perform uploads and downloads.
However when they're deployed separately in docker they don't work
I made a post on this here:
https://stackoverflow.com/questions/58531963/how-to-use-django-file-storage-to-share-files-between-an-api-and-a-worker
I'm confused why I can't retrieve files from the storage file system using the default_storage
What is the idiomatic way for a worker to retrieve something from Django's file storage that does not involve retrieving from the database?

native tide
#

@last lily it depends, in django you can apply CRUD functions quite easily but you'd probably need to take a course to understand django and CRUD. There are a lot of courses for django on udemy and i'm sure there are a lot of tutorial series on youtube. For me, Django projects are very comprehensible even for a person unfamiliar with it.

native tide
#

Idk if this is that much web dev related But When I run my python script with a request.get() I get a remote disconnect Error over And over

#

It works for a bit And then it stops

#

Worked last week

#

I talked with the server owner And he said No issues were seen on his end?

rigid laurel
#

Try requesting to the end point in a different way. Possibly worth checking out postman

soft chasm
#

i have a stupid flask question: what's the difference between server side session variables and just storing something in a global dict? i know global is normally a byword for 'terrible idea' but in this case it fits, if the user id's are unique, right?

native root
#

Unless you're using something like flask-sessions, as far as I'm aware flask does not have server side session variables

#

Since flask applications are often single-namespace applications, then yes a global dict with unique user id's would function as a server side session manager

#

The session you get from flask is a client-side session stored inside a regular cookie passed back and forth between the browser and your flask application

#

the docs state

#

If you have set Flask.secret_key (or configured it from SECRET_KEY) you can use sessions in Flask applications. A session makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. The user can look at the session contents, but can’t modify it unless they know the secret key, so make sure to set that to something complex and unguessable.

#

The key also by default includes a timestamp, preventing reusage of the cookie after (default 31 days) from that date

soft chasm
#

Yep been working with the flask.sessions extension and flask_login

#

Ty for notes

urban laurel
#

Hey guys, im just starting out with webdevelopment and have worked a bit with .NET Core for my backend and angular/ts for the frontend stuff. i also did some python before and rly liked the language so i thought maybe python would be a good alternative for my webdevelopment stuff.
i understand that there are a few popular frameworks like django and flask among others in python for this matter, but before i research every single one of them i thought i might as well ask you for recommendations and resources for beginners on that matter. maybe some of you worked with .NET Core and angular before and know of frameworks that would be easier to get into for ppl with that background.

vagrant adder
#

I have worked a bit with .net

#

I liked flask because it feels like legos, you have a lot of extensions that do something, but you can write apps without much extensions

#

And django is like a big bag with every single wrench you'll ever(probably) need

#

Orm, forms, api-like tools etc

#

Try both then decide i'd say

urban laurel
#

so that is the "batteries included" thing with django then and flask does not subscribe to that philosophy?

#

and did one feel more familiar to how things are done in .net to you or are both about the same?

vagrant adder
#

I think django has that .net feel but i really loved flask

#

You can write a server under 6 lines

urban laurel
#

ok thank you

vagrant adder
#

Corey schafer has tutorial series on both django and flask

#

Really good resource

urban laurel
#

so, django seems to be a rather old framework, at least it was introduced over 10 years ago... does that mean it is lacking in some way to newer frameworks or is it just frequently updated?

vagrant adder
#

Nope

soft chasm
#

flask is amazingly easy to get stuff up and running in literally seconds with

#

just my 2 cents πŸ˜›

candid basalt
#

Django vs Flask is a long lasting debate.

#

Both are good for their own purposes.

vagrant adder
#

Django was introduced a long ago but dev team is constantly working on it

candid basalt
#

Both are very powerful and up-to-date.

vagrant adder
#

A lot of big companies are using django

urban laurel
#

thats good to hear

vagrant adder
#

Google, instagram

candid basalt
#

The only thing you may decide based on is if you want batteries included or want to build/collect/attach everything yourself.

vagrant adder
#

And my last company used it for their admin panel :p

#

You'll really get far using django but you might give flask a try

#

And see what fits your needs

urban laurel
#

but if i understand correctly they are both backend frameworks, not fullstack

#

right?

soft chasm
#

they both do templating i think

candid basalt
#

Flask doesn't deal with templates afaik. You'll have to use jinja or something for that.

#

Django does have it's templating system included yes.

vagrant adder
#

Backend only, but they have templating engine

#

Like twig for js

soft chasm
#

oh right, yeah it's through jinja2 but it works well

vagrant adder
#

Oh yeah

#

@candid basalt
Flask has jinja2 and has ability to render html

soft chasm
#

i mean, i don't feel like jinja was an extra thing i had to go out and 'get' to make flask sites work

candid basalt
#

Flaks and Jinja are 2 tools working well together. Django and it's templates is the same tool thats works well with itself... xD

vagrant adder
#

Yes

candid basalt
#

Both are very viable, but I would go for Django if you want something moderately complex working well fast. Go for Flask if you need something very simple or something very complex (that complex so that even Django's customization doesn't cut it).

urban laurel
#

that is good advice, thank you

candid basalt
#

Also there are edge cases you may want to take into account.

#

Pretty often whatever module you use for Flask pretty often can be used with Django too.

#

On the other hand Django's ORM does not like to deal with document-based DBs like mongodb.

#

For obvious reasons.

#

So it very much depends on your particular use case.

soft chasm
#

i actually have a question about flask, i often see people say never use it in production, use a proper server, does that mean re-doing it in something totally different, or is it just i need to fiddle stuff to get the flask backend to use a different server framework?

urban laurel
#

im currently using ms management studio to manage my ms sql server if that is relevant @candid basalt

candid basalt
#

They probably mean don't use flask's development server.

#

And use some kind of wsgi-capable frontend like gunicorn instead.

#

Flask itself is more then ok in production.

soft chasm
#

ah okay

#

is the dev server just if i have debug on or that's different?

#

ah just looking at it now i guess not...

candid basalt
#

This is what i'm referring to. flask run - don't do it in production.

soft chasm
#

got it

#

ty

#

so this is the same as just app.run() in python right?

candid basalt
#

I believe so, yes.

#
The alternative way to start the application is through the Flask.run() method. This will immediately launch a local server exactly the same way the flask script does.
vagrant adder
#

@soft chasm
When you do flask run, flask's own dev server starts and that webserver sucks and should never been used in production

#

You can use gunicorn to server that same exact app by gunicorn run:app

#

run -> run.py -> file name where there is Flask instance

#

And app is Flask instance

elder nebula
#

I should learn to use django tests, do you know any good tutorials for that?

candid basalt
#

Django official documentation should be a good start if you know what testing is.

#

Otherwise you may want to study testing overall first.

urban laurel
#

nvm, found it on their site under /downloads .. did not anticipate it there

dense hound
#

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.```
#

how can I fix this error when I try to add a key:value session

#

in flask

native root
#

Sessions are per-user, and as a result they apply to the current request by default

#

if you try to add to session outside of a request, which session should it apply to?

native tide
#

hi guys

#

i'm successfully creating a docx with some data on a django. Now i was wondering how could i create a link to make that file downloadable

#

i don't want the media folder to be exposed on the urls i want to give the user one time url which they will use to download the file

#

can someone give me what i should look into here

tall pecan
#

how to pass parameters in redirect() without displaying those parameters in URL?

#

current code is

@app.route('/check_user', methods=['GET', 'POST'])
def check_user():
    uid = request.args.get("uid")
    uname = request.args.get("uname")
    avid = request.args.get("avid")
    return "Your UserID: "+uid+'\nYour Username: '+uname+'\nYour AvatarID: '+avid

@app.route("/authentication")
def authentication():
    #some stuff
        return redirect(url_for('check_user', uid=str(userid), uname=str(username), avid=str(avatar)))
vagrant adder
#

return reditect(url_for('some_func), page=1, something= "something2")

#

To not show in url?

#

Umm

#

You'll need to redirect to some url and then pass some json data

tall pecan
#

ok

native tide
#

how do you put a pygame application in a Flask webpage

#

i want to put my pygame project on my website

native tide
#

???

tired root
#

@native tide It does not work this way

#

for a game to work with a browser, it needs to written in HTML5

#

Python is like PHP - a server side language

#

not a client side one

native tide
#

oh noooo

tired root
native tide
#

ok, than i want to make a downloadable version. and put the APK on my website for people to download it

tired root
#

Then you have to use Kotlin or Java

#

Or Unity Engine etc

#

Maybe you should read up on how these things work

native tide
#

oh well

tired root
#

Have a look at Godot though

native tide
#

So that module

tired root
#

I think that can do Python and transfer to Android

#

But tbh, those are all just wrappers and you give up a lot of control

native tide
#

turns python code into javascript

tired root
#

basically yes

native tide
#

interesting

tired root
#

But if you want to put a game on Android, I really urge you to use Unity

#

There is a lot of things about Android you don't know about and Engines take these issues away from you

#

such as the metric fuckton of resolutions you have to care about

#

Unity abstracts this by working with relative units

native tide
#

but using unity means learning C# right?

#

or Javascript

tired root
#

C#

#

yes

#

If you want to do webstuff, there is no way around JS anyway

native tide
#

man

#

yeah i have to learn JS anyway sins i am digging deeper into webdev

tired root
#

Here, this is what a renderloop looks like in JS

#

Thought you might be interested

#

@native tide

native tide
#

hmmm

#

js looks like a mix of python an c#

#

so its not a normal loop?

tired root
#

it is, you just have to wrap it in requestAnimationFrame()

#

and there is no guarantee that every frame is rendered

#

but it is not a while loop, no

native tide
#

for loop it is

tired root
#

Okay, last try asking this..
This is my login code:

@admin_app.route('/admin-login', methods=['POST'])
def admin_login():
    uname = request.form['admin-name']
    pwd = request.form['admin-password']
    user = User
    if (db_get_admin_login(uname, pwd)):
        user.is_authenticated = True
        login_user(User(1))
        return redirect(url_for('overview'))
    else:
        return redirect(url_for('login', il=True))

In the flask login documentation, it says I need to validate the "next" parameter:
https://flask-login.readthedocs.io/en/latest/#login-example

However, such a param does not exist, if I try to print it, it returns None. I am also not using the DB schemas coming with flask or SQLAlchemy. Can I ignore it then? Can someone shed some light here please?

native root
#

The docs are assuming that you pass a ?next=/next/url to your login form, which allows it to redirect to a new, user-specified destination

#

you are not doing this, so you can ignore it

#

The reason they discuss it is if you do that step improperly (since you're not doing it all it doesn't matter for you) ?next=https://google.com/ might work, which would not be a good decision.

tired root
#

THanks Bast. Took a load off my mind.

marsh canyon
#

How can i make a html section 100% of view port

#

i want the #welcome-section element to be 100% of the view port

#

height = 100vh dosent really work

tired root
#

There is a typo in position:absosute;

#

in #welcome-section

#

@marsh canyon

ebon beacon
#

Hello all

#

I am new to Flask

#

I copied a project I began in a computer to my personal PC

#

i'm now trying to test the application, so I ran

#
python manage.py test
#

But I'm getting this error

#
Traceback (most recent call last):
  File "manage.py", line 4, in <module>
    from flask_migrate import Migrate, MigrateCommand
ModuleNotFoundError: No module named 'flask_migrate'
#

Do I need to re-download flask and other dependencies?

ebon beacon
#

Ok. I had to re-install dependencies

primal drift
#

How do I convert model.datefield into integer so I could substract 2 date to find the duration between that date

#

or is there any model that could simplify it? cuz I've been looking at the django model doc and ain't found any solution

soft chasm
#

You should really hash those pws @tired root :P

#

(afaik)

native root
#

@primal drift You can subtract two dates alone to find the duration between, and .total_seconds() the difference for it in seconds

marsh canyon
#

still dosent work @tired root

#

if you run the free code camp test, the test is still showing up

primal drift
#

@native root nvm, I just gave up and use time module, though it will consume lil performance and more code... but it works... thanks for the reply tho πŸ™‚

native root
#

@marsh canyon you need box-sizing

#

your padding is adding to your height, making it 100% + 150px

#

box-sizing: content-box makes the width not contain padding or border

#

box-sizing: border-box does

marsh canyon
#

if i remove padding how to make the text come down

native root
#

No need to remove

#

add box-sizing: border-box to #welcome-screen

marsh canyon
#

okay

#

yay awesome it works

#

thanks a lot

native root
#

πŸ‘

#

If you wish to center it properly, look into flexbox

marsh canyon
#

okay

tired root
#

@soft chasm How do you know I am not?

#

Because what you don't see is db_get_admin_login and that function is defined like this:

#------------------------------------------------------------------------
def db_get_admin_login(user:str, pwd: str):
#------------------------------------------------------------------------
    cursor = get_database().cursor()
    try:
        cursor.execute("""
                        SELECT id_pi_settings
                        FROM t_pi_settings
                        WHERE backend_username=%s and
                        backend_password=crypt(%s, backend_password);
                       """, (user,pwd))
        result = cursor.fetchone()
        if (result is not None):
            return bool(result[0] == 1)
       return False

    except psycopg2.Error as err:
        print(err.pgerror, file=sys.stderr)
        return False```
soft chasm
#

Ah sorry right you are, didn't parse that there was a gen fn call there, my bad

native tide
#

so the only way to put a game on your website

#

is your game needs to be made with JavaScript

#

and your website shouldn't be build with flask

#

is that right?

primal drift
#

how do i navigate in a section on the same page using django url tag

#

example localhost:8000/#section2

#

how do i get that section 2 and not getting navigate at the top of the page

azure gyro
#

I want to create a web dashboard for my bot. Is there any recommendation on which framework I should use? And should I write an API or directly access the database?

tired root
#

@native tide No, you CAN build your website with flask, but the actual game must be done in HTML5, which includes Javascript

#

The actual game is just within a <canvas></canvas> tag

#

@primal drift You need to set an anchor, like <a href="#section2">TEXT</a>

#

@azure gyro Either user Django or Flask. Wether you access the database or use a REST API, depends on the general design and if the connection/credentials to the database can be secured.

native tide
#

how to write games with HTML5?

#

can you give me some suggestions?

#

for tutorials and such

#

@tired root

tired root
#

It makes it a lot easier

#

@native tide

#

I also recommend typescript over directly using JS

native tide
#

oh thx

#

what is TS though

tired root
#

Typescript compiles to javacsript

#

but allows for more strict typing and better programming

ornate crest
#

ooooof

signal karma
#

What framework is recommended in Python community for Web development? It's kind of tough to choose. I hear about Django, Flask, Connexion, Tornado, etc. It seems like everybody has its own favorite.

soft chasm
#

hey i'm in an environment where i need to run my py scripts with python3.6 script.py, which works fine except when i try to use gunicorn to run my flask app, any ideas?

#

i can't seem to get it to point to that python version so a bunch of packages don't load

#

i have it installed in my pyhton3.6 dist packages

#

but from memory i also once tried to make my default python 3.6 via bash alias and that broke a bunch of stuff :/

native root
#

try python3.6 -m gunicorn ...

flat mirage
#

hello guys

#

I am having a problem getting my data from my api

#

it returns null on my console

#

But I can insert data to my database through POST

#
console.log(response.data);
}):```
#

that service returns null

vagrant adder
#

@signal karma
Django and flask are 2 of the most popular, i would say try both of them and see what fits you

signal karma
#

@vagrant adder a requirement I am asked for is auto swagger doc generated, any of those 2 supports this well?

vagrant adder
#

Flask has got you covered

#

But with one extension

signal karma
#

ok, any recommendation?

vagrant adder
#

What are you trying to build

#

Api?

signal karma
#

yes

vagrant adder
#

This is a good article

signal karma
#

thx πŸ˜‰

hollow root
#

Django:

Can i get some logica help here, I need to create a list of objects from the past 12 months, but i need 1 point for each of the months. The currency_data contains a QS of daily objects of the past 4 years

this is what i currently have:

now = datetime.now()
first_of_this_month = now-timedelta(days=now.day-1)
one_year_back = now- timedelta(days=365+now.day)
current_year_filter = currency_data.filter(formatted_date__range=[one_year_back, first_of_this_month])
past_year = []

# get past year data
for i in range(1, 13):
    if current_year_filter.filter(formatted_date__month=i).last():
            past_year.append(current_year_filter.filter(formatted_date__month=i).last())```

This gives me 12 data points, but it is ordered incorrectly, so here is an example of what i get.

[Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 18, Nov 18, Dec 18]


And this is what i am looking for.

[Nov 18, Dec 18, Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 19]

proper hinge
#

Can't you do an order_by on the date column to fix that?

#

or will it not sort properly due to how the date is formatted?

#

(which would probably be a good reason not to store dates in such a format to begin with)

hollow root
#

the formatted_date is a datetime object so the arrays are a list of datetime objects that i just made readable for the questiion. But i did try an order_by('formatted_date') now but it doesn't seem to work.

#

I've tweaked the QS a little and im getting better data back, just need do get the order sorted now.

proper hinge
#

I can't think of why the order_by would fail then

hollow root
#

Yeah im doing something wrong somewhere, will add the updated code and responses in a little.

hollow root
#
past_year = []
        now = datetime.now()
        current_day = now.day
        one_year_back = now - timedelta(days=365+current_day)

        current_year_filter = currency_data.filter(
            formatted_date__range=[one_year_back, now]
        ).order_by('formatted_date')
        # get past year data
        for i in range(1, 13):
            if current_year_filter.filter(formatted_date__month=i).first():
                past_year.append(current_year_filter.filter(formatted_date__month=i).first())

gives me

[Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 18, Nov 18, Dec 18]```

and im looking for
```[Nov 18, Dec 18, Jan 19, Feb 19, Mar 19, Apr 19, May 19, June 19, July, 19, Aug 19, Sep 19, Oct 19]```
proper hinge
#

Ah

#

It's pretty obvious now I think

#

you use i as the month

#

and you start at 1

#

you append in the same order

#

so of course 1 corresponds to January

hollow root
#

Riiiiight, very true, thanks!πŸ˜… let me see if i can work with that

proper hinge
#

Unfortunately my django chops are not that great

#

I wonder if distinct() works

#

but like with formatted_date__month rather than the entire formatted_date

hollow root
#

Hmm, its worth a shot, ill have a look

proper hinge
#

I don't know how that would work with the ordering

#

if it would respect it and keep the first 1

#

Oh

hollow root
#

oh thats neat.

#

thanks gonna try that out in the console a little and see if i can work with it.

#

Thanks @proper hinge Looking a lot better now! πŸ˜„

proper hinge
#

Np

hollow root
#

this ended up giving me what i was looking for


year_dates = current_year_filter.datetimes('formatted_date', 'month')

        # get past year data
        for item in year_dates[1:]:
            if current_year_filter.filter(formatted_date__month=item.month, formatted_date__year=item.year).first():
                past_year.append(current_year_filter.filter(formatted_date__month=item.month, formatted_date__year=item.year).first())
flat mirage
#

hello guys
how can I delete data in my mongodb using model in python

@classmethod
def delete(cls, province_code =None, province_name=None, **kwargs):
self = cls()
province_id = ObjectId(kwargs["id"])
self.__province = self.__db.province.delete_one({'_id': province_id})
return self

that code above says

AttributeError: 'Province' object has no attribute '_Province__db'

soft chasm
#

@native root says gunicorn is a package and cannot be directly exectued

vagrant adder
#

gunicorn filename:appinstance
@soft chasm

soft chasm
#

This is what I tried originally @vagrant adder and it fails for versioning issues

vagrant adder
#

Versioning?

#

What's the issue

pliant hound
#

This is outside of the scope of web development, but has anyone run into issues with internet connection and the built-in firewall in MacOS Catalina?

#

The problem started out of the blue for me today. Spent two whole hours on the line with a senior tech who ended up having me ship off logs

#

While the firewall is active, my laptop is served a self-assigned IP address

#

the second I turn off the firewall, poof- everything works as expected

vagrant adder
#

I feel like this is more appropriate in #unix

pliant hound
#

fair. Thanks fella πŸ™‚

ebon beacon
#

please what is the equivalent for decimal(8,2) in SqlAlchemy?

#

I'm declaring models for tables

#

Would

db.Numeric(8,2) 

suffice?

#

Hello?

vagrant adder
#

Just a sec

#

The answer i linked is explaining what are those integer parameters

#

@ebon beacon

ebon beacon
#

@vagrant adder thanks!

vagrant adder
#

πŸ‘

left thorn
#

hello, I am trying to use this library https://github.com/nbubna/store and I am very confused as to why the code in "clear()" only works if i put it in "load()"
https://pastebin.com/qD5wGWf6

<script type="text/javascript">
  function load()
  {
    var cart = store.namespace('cart');
    var element = document.getElementById("ingall");
    console.log(store.cart.getAll());
    element.innerHTML = "Ingredients:".concat(store.cart.get("topping"),"\n\nAllergy Information:");
  }
  function clear()
  {
    var cart = store.namespace('cart');
    cart.set('topping', "");
    load()
  }
</script>```
#

the pastebin is the entire page

tired root
#

The code should work in a onclick event as well

#

I don't see a reason why this shouldn't work.

vagrant adder
#

he forgot ; on load in clear function but i'm guessing that doesn't matter

native tide
#

A question about CSS: if I set position: relative to the 1st image and position: absolute to the 2nd one, the 2nd image will use the 1st one as a reference, right?

native root
#

No

#

Relative/absolute are relative/absolute to their closest non-static parent element

native tide
#

Um, I think I know what you meant

#

πŸ€”

novel ledge
#

Hi there, I am trying to make a progress bar for my Flask App that is collecting tweets from the Twitter API (using Python). If a hashtag is entered and the user hits the submit button, I am hoping to have a progress bar while tweets are being collected. I have a cap to the amount of tweets being collected so my plan is to track the number of iterations for each tweet and divide that by the cap as my loading bar. I was just wondering how I would go about this, like is there a way to pass python variables into Javascript so that it could maybe update like every 10% or so (better yet continuously). For context, I'm very new to web stuff including Flask and have never touched Javascript. Thanks

lapis stratus
#

Hello

#

I had a planned to go in Web Development.Do I need to learn the HTML,CSS,JS and OOP of python?

safe garden
#

depends on whether you’d want to work with frontend or backend

#

html, css, and js are used in frontend web dev

#

so youd need to at least know the basics of those languages

#

all frontend python web dev uses some form of html/css

#

though python can be used in backend, along with js

lapis stratus
#

Thanks @safe garden

junior cloak
#

@lapis stratus If you want to make stuff on your own, in a small team, or are aiming for a full stack job, yeah, knowing them all helps. But these aren’t small things to learn. You can pick up the basics quickly but you aren’t going to be a wizard at them all in a hurry. If you’re aiming more for backend development or any sort of python-specific job at a place big enough to have separate people doing front end and backend, then focusing on the python part is fine, specifically building REST APIs and such and mostly only have to care about the JSON you’re outputting or whatever

lapis stratus
#

Thank you for @junior cloak you

#

you are correct bro (Y)

gleaming herald
#

This is the code from fastapi website

#

Why does this not work

vagrant adder
#

What is the error

vocal fox
#

Hello !, guys im doing a app that generates files based on a web form, for example, i ask the name of the web, generate a folder , a index.html, with the contents of the form.
but they have to load the page again, to make another file, how can i ask, how many pages do you need to create, and add a form asking data for each page?

timid sphinx
#

And I am trying to move it down

#

This is what I have: (The top part is what I have and doesn't work.) The second part someone else did and adds the background to it

#

I selected the .widget-area, why is it not moving with top?

junior cloak
#

Possibly being overwritten by something else. Devtools inspector will tell you. Also not sure what you are trying to do but you probably want to use margins and not just positioning

#

@gleaming herald you get it working? what's the error?

native tide
#

Hi webdevsπŸ‘
What's the difference between id and class? When I'm using css they all look the same

#

like for example python div#menu { #stuff }
And python div.class_name { #stuff }

#

Forget the #stuff, I'm getting used to html5 comments :D

junior cloak
#

@native tide class can and should be reused across many similar elements, id you only use on one element

#

these days in practicality you should almost never be using ids

#

for modern js frontends and stuff you may use an id on the root element and that's it

#

but don't use an id if you don't have a reason to. even if it's for an element that you think "oh i will only have one of these on the webpage". still do not use it

#

only use it if you absolutely need to be able to target that one specific element for some functionality reason and will never use the same element again somewhere else (there aren't as many situations these days where this is the case)

#

it also makes css more difficult because there is different specifity applied to ids versus classes and you can get unexpected results

#

basically just try not to use ids haha

native tide
#

Thank you for the response, I'm gonna use classes now. The tutorial is from 2013 so I guess that's why he was using a lot of id's

junior cloak
#

oh gosh

#

i dont know the tutorial you are using but having said that i would probably never look at it again

#

so much is different, and better

#

i cannot begin to describe how frequently when debugging with someone it's because they are using a tutorial from a few years ago and everything changed since then haha

#

at best, you may be learning things that are valid but not necessarily current practices at all (the class/ID thing became especially important after frameworks like React came out... which was probably after your tutorial)

#

at worst, you could be doing things that just dont work anymore

#

(for css and stuff, it will all work still. but many newer things have come out since then that will make your life easier)

#

for myself, i usually filter google searches on tech-related things to results from within the last couple years

native tide
#

πŸ‘ that's good

hoary spruce
#

I'm currently creating a flask tool. But I have tons of <input>'s that the user has to fill in. talking about 100+. And I need to save all those inputs in a database.
But is there a way to do this:
inputField= request.form['exampleInputField']
Much faster? Like instead of doing that for every single input?

native tide
#

@hoary spruce idk about flask, I'm just a newbie, but why don't you create a class for these inputs and then do what you want to do with them? You only need to say what's going to happen with this specific class once.

#

I guess the concept of classes is the same in any language

rigid laurel
#

You could grab the whole requests.form as a dict I think

tired root
timid sphinx
#

is there a way to extend the background color outside the container? Making just the background color makes it seem like it is getting cut off, I want the white background like 50 MORE pixels to the left and right

#

with css*

tired root
#

use padding to extend the container

#

@timid sphinx

#
padding-left: 50px;
padding-right: 50px;
#

I really want to advise you against using pixels though. Use percentage or vw/vh

timid sphinx
#

@tired root

#

That fixed it by the way, thank you

native tide
#

how do i put text that is entered in a form tag in a variable

#

so i can use it in a python script

#

let me just say what i want to achieve:

#

i've made a script that sends emails with flask.

hollow minnow
#

Hey could i get an opinon on this way of 2FA?

class Register(Resource):
    def post(self):
        parser = register_parser()
        args = parser.parse_args()
        email = args['email']
        tfa_code = str(str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)))
        match = mongo.db.registrations.find_one({ 'email': email })
        if match:
            print('Found')
        auth = (mail_settings['MAIL_USERNAME'], mail_settings['MAIL_PASSWORD'])
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(auth[0], auth[1])
        msg = EmailMessage()
        msg.set_content('Your Authentication Token Is: {}'.format(tfa_code))
        msg['Subject'] = "Your psty.io 2FA Code"
        msg['From'] = "psty.io <support@psty.io>"
        msg['To'] = email
        server.send_message(msg)
        entry_obj = {
            'email': args['email'],
            '2fa': tfa_code
        }
        if not match:
            mongo.db.registrations.insert_one(entry_obj)
        else:
            mongo.db.registrations.find_one_and_replace({'email': str(email)}, entry_obj)
        resp = make_response({'msg': '2FA Sent Successfully'}, 200)
        resp.set_cookie('email', email)
        return resp

class Confirm(Resource):
    def post(self):
        parser = confirm_parser()
        args = parser.parse_args()
        tfa_code = args.get('tfa_code')
        cookies = request.cookies
        if not cookies.get('email'):
            return redirect('https://psty.io/signup', 200)
        email = cookies.get('email')
        register_obj = mongo.db.registrations.find_one({ 'email': email })
        if tfa_code == register_obj:
            resp = make_response({'msg': 'Logged In!'}, 200)
            resp.set_cookie('authentication_code', auth_code)
            return resp
        else:
            return { 'error': '2FA Failed!' }, 302```
native tide
#
from flask import Flask, render_template

app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAX_EMAIL_SENDER'] = 3

app.config['MAIL_USERNAME'] = 'testkenny00@gmail.com'
app.config['MAIL_PASSWORD'] = '###########'

mail = Mail(app)


@app.route('/')
def index():
    msg = Message('This is a test send email', sender=('kenny', 'testkenny00@gmail.com'),
                  recipients=['hoftkenny3@gmail.com'])
    # msg.body = "testing the email sender"
    msg.html = "<b> this is a tested email for me to test testing</b>"
    mail.send(msg)
    return render_template('play.html')


if __name__ == '__main__':
    app.run(debug=True)
hollow minnow
#

you need a request parser

#
def register_parser():
    parser = reqparse.RequestParser()
    parser.add_argument('email', required=True)
    return parser```
#

and then i call it like this inside my class:

class Register(Resource):
    def post(self):
        parser = register_parser()
        args = parser.parse_args()
        email = args['email']```
native tide
#

i want to take tha variable from my html script

hollow minnow
#

yes

#

in your HTML

#

post the form to your URL with the endpoint for sending the email

#

have the variable be an input in the form with the prop name='email' or somehting so this would be the email argument

native tide
#

the name part i get, but the rest seems

hollow minnow
#

seems..

#

?

native root
#

Your 2FA code seems alright, although there are two issues from what I can see. First is that email is not the best--allowing attachment for something like lastpass authenticator or something might be better. The second is less opinionated, which is that you don't seem to have a reset/ratelimit. Someone can repeatedly try to guess the auth code without triggering a lockout or a code reset

hollow minnow
#

@native root i have a ratelimit

#

u just cant see in the snippet

native root
#

Good to know

#

then it seems fine

sonic scaffold
#

Why not use TOTP seeds like the rest of the world?

#

(you don't have to answer, it might be a dumb question)

hollow minnow
#

this is for free passwordless accounts that aren't paying for any special services except storing pastes for longer than 1 day, so im not really trying to make it that robust for features for that side. im planning on adding a subscription based account tier eventually with much more capabilities and that will actually have a password and what not so i would have OAuth options there for login with.. type deals.

#

also keeps the space taken up on my free mongo instance low zoomeyes

sonic scaffold
#

I see, so it's not the kind of thing a lot of users would be willing to set up TOTP storage for.

#

Sounds neat, though - I gave Pastebin money, so it's a good business idea

hollow minnow
#

its basically just pastebin but with file hosting as well

#

and im about to do a huge overhaul, ive overhauled the backend so now im just adding new features and eventually new UI

#

dont trash the UI i made it in 45 minutes its trash ik

sonic scaffold
#

Neat!

hollow minnow
#

πŸ‘

#

thanks for the opinions guys

#

i appreciate it!

timid sphinx
#

damn up to 100mb per file

#

must have lots of spare storage

timid sphinx
#

So I have Billing and Shipping on the left, then payments on the right. I am using wordpress and swapped themes which caused this. At first it was Billing on the left, Shipping on the right, then payments below it. Is there a way using CSS to swap it so shipping is below them and shipping is NEXT to billing

tired root
#
            {% if data['format'] == "mp3" %}
                <option selected value="mp3">mp3</option>
                <option value="aac">aac</option>
                <option value="ogg">ogg</option>
            {% elif data['format'] == "aac" %}
                <option value="mp3">mp3</option>
                <option selected value="aac">aac</option>
                <option value="ogg">ogg</option>
            {% elif data['format'] == "ogg" %}
                <option value="mp3">mp3</option>
                <option value="aac">aac</option>
                <option selected value="ogg">ogg</option>
            {% else %}
                <option selected value="mp3">mp3</option>
                <option value="aac">aac</option>
                <option value="ogg">ogg</option>
            {% endif %}
``` Anyone got a prettier way to write this? I doubt it, but maybe I overlook something
sonic scaffold
#

Can you do something like

{% for format in ('mp3', 'aac', 'ogg') %}
    <option {% if format == data['format'] %}selected {% endif %} value="{{format}}">{{format}}</option>
{% endfor %}```
#

not sure if you can define a tuple like that in a template

#

it doesn't handle your default case, though

native tide
#

so ununderstandable

hollow minnow
#

@timid sphinx they are removed everynight at Midnight EST

#

so unless somebody fills up 1TB in 24hrs

#

im good

#

thats why i have rate limits lol

dim stag
#

Is using pandas for data operations in a full stack web app a terrible idea? Let's say target data is complicated enough to be annoying to handle without dependencies, but wouldn't be impossible either

native tide
#

What is best way to do frontend for blog ?
I am using Flask as backend and Postgres as database and I need suggestions

#

Its been botering me and I cannot figure out what to use

#

I am scared of javascript tbh

sonic scaffold
#

You can do a blog in just plain HTML and CSS easily - use CSS grid and you can even make it responsive

native tide
#

really ?
I was thinking about combo of Vue.js + Bootstrap

#

since I really like to work database, server, backend

#

devops stuff

tired root
#

@native tide I recommend doing a static blog. The issue with dynamic blogs is, that your attacker has a lot of angles to attack you. I myself use Jekyll for my blog and it serves me well. I have basically my own github pages at home, with a git server on my NAS and a post commit script that runs Jekyll on my Pi to generate the site and then uploads the changes to my webserver via SSH. The attacker has no angle to actually attack my blog, since it is all HTML only. Sure, he can attack the web server, but that is out of my hands. The issue you run then into, is the search, but I have written a REST api point for that and Jekyll generates a SQL file with the content and there is a database for that. But it is so tied down with read only access, an attacker cannot insert anything, even if he got control of the user, because it has no rights to insert anything. So he needs to hack the server, if he wants to do bad things.

#

Overall, using a static blog served me well and I cannot recommend it enough

native tide
#

@tired root I would recommend you to use CI/CD pipeline and replace that script

tired root
#

Uhm, this script is basically a continoous deployment script

native tide
#

I think Jenkins could do that

#

or Gitlab-CI