#web-development

2 messages Β· Page 146 of 1

karmic flare
#
body {
  background-image: url('static/img/bg.jpg');
}
#

the rest of the css seems to load just fine

#

it still doesn't work with btw :

body {
  background-image: url('../static/img/bg.jpg');
}
indigo kettle
#

is that exactly what you're writing?

#

is /static coming off the root domain?

#

maybe you just want
background-image: url('/static/img/bg.jpg');
? @karmic flare

native tide
#

Has anyone ever tried to do webscraping the twitter website. I keep getting this as HTML response:

<p>We've detected that JavaScript is disabled in this browser. Please enable JavaScript or switch to a supported browser.</p>

As others have suggested me, I also tried using Puppeteer. But this gave the same error :(. This is the code I used:

const puppeteer = require('puppeteer');

(async () => {
    let twitterUrl = 'https://twitter.com/home';

    let browser = await puppeteer.launch();
    let page = await browser.newPage();
    await page.setJavaScriptEnabled(true);
    await page.goto(twitterUrl, {waitUntil: 'domcontentloaded'});
    
    let bodyHTML = await page.evaluate(() => document.body.innerHTML);

    console.log(bodyHTML);

    await browser.close();

})();```
Or is it simply impossible because Twitter blocks web scraping so they don't overload their servers? Has anyone ever had this problem?
I also know the code above is not Python but Javascript but scraping twitter with python gave me the same error.
karmic flare
distant trout
#

should i limit one useEffect per component?

#

or can i have multiple?

indigo kettle
#

you can have multiple

#

many times you have to

#

@distant trout

distant trout
#

ahh

#

im calling an api to refresh an access token, but it does it everytime the component is rendered

indigo kettle
#

useEffect's second argument tells it when to run. You often do not want them running at the same time

distant trout
#

the empty list

#

i passed in an empty dependency list

indigo kettle
#

the empty list tells it to run on mount and then never again

#

unless it gets remounted

distant trout
#

is mount == render?

#

so when the component is first rendered

indigo kettle
#

basically

#

if it gets removed from the page and the put back on the page, it will run again

distant trout
#

ahh i see

#

if i pass in a state in the dependency list, it will only run when the state changes?

indigo kettle
#

yes

distant trout
#

got it, thanks

indigo kettle
#

πŸ‘

plush socket
#

Guys do youu know where can i ask for bs4 help

proper hinge
native tide
#

anyone could help me with selenium.common.exceptions.ElementClickInterceptedException: ?

#

i send values to email input then send click on submit but when i try to send click on submit again it gives me selenium.common.exceptions.ElementClickInterceptedException:

#

here whati have tried

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

native tide
#

done

#

!code

last patio
#

Trying to migrate
getting psycopg2.errors.StringDataRightTruncation: value too long for type character varying(18)

opaque rivet
#

that's a JS job, you should look into jquery

slender whale
#

I'm looking for some advice here. I want to create a website that will link blog stories that can be commented on as well as have a twitter feed. Django/sqlite/react seems like the backend/db/frontend I want to do

#

But I'm super new to web frameworks so, any advice would be great.

abstract forge
#

Is there a "best" or recommended oauth2 library? (client)

#

actually, I'm using aiohttp already, so I suppose I should just use aiohttp-oauth2

icy drift
#

Like for example I want to have 3 pages but I want different background for different pages

stable hemlock
icy drift
#

Ya if I thought of that πŸ€” but I want to render the page dynamically

#

So will I have to use any other method

#

Like we do int:pk/ thing

#

Just keeping the format same and render different data

#

So by that I will be having only 1 html file and by templating I will be filling data , so is there any way to change background also like that @stable hemlock

stable hemlock
#

You could feed the css url as a variable. @icy drift

ashen sparrow
#

hi guuys, can I make a landing page in react, build it into html,css,js and display that as a template in a django app ?

#

Only asking this for a single page and not the whole project.

sly canyon
#

@ashen sparrow I believe your react app is intended to be standalone, it runs independently of your back-end. In this case, I believe it's recommended to only serve data/json through your backend. So. basically you'd make an API for your react app

livid thunder
#

Why does this always say "invalid CREDENTIALS"

def customer_login(request):
    
    if request.method == "POST":
        email = request.POST['email']
        password = request.POST['password']
        user =authenticate(email=email, password=password)
        if user is not None:
            return redirect('homepage.html')
        else:
            messages.info(request, "INVALID CREDENTIALS")
            return redirect('/customer_login.html')
    else:
        return render(request, 'customer_login.html')```
#
class customer(AbstractBaseUser):

    firstname = models.CharField(max_length=30)
    middlename = models.CharField(max_length=30)
    lastname = models.CharField(max_length=30)
    # email= models.emailField()
    email = models.EmailField('email address', unique=True, db_index=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    USERNAME_FIELD='email'```
pulsar timber
#

hey is it possible to control a python script running on a vps using a website based on php backend

#

i really wanna know

severe apex
#

Somebody can help me with my flask app

#

But my FLASK_APP location is there

smoky skiff
#

take screenshots and not pictures of your monitor

severe apex
#

Can you help me

cedar pasture
#
for i in range(X_FUTURE):
            curr_date = curr_date +  relativedelta(months=+1)
            dicts.append({'Predictions': transform[i], "Month": curr_date})
            

        new_data = pd.DataFrame(dicts).set_index("Month")
        ##df_predict = pd.DataFrame(transform, columns=["predicted value"])

        new_data.to_csv(os.path.join("downloads", index = True, encoding='utf8'))

        labels = [d['Month'] for d in dicts]
            
        values = [d['Predictions'] for d in dicts]

        colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values, filename = filename)


@app.route('/download/<filename>')
def download(filename):
    return send_from_directory("downloads", filename, as_attachment = True)     
#

<a href="{{ url_for('download', filename=filename) }}">Download</a>

#

Hi community, I m trying to save my to_csv into os.path.join and return the csv file from download button in HTML page, currently I m getting this error TypeError: join() got an unexpected keyword argument 'index', Does anyone excel in flask python, please correct me ~ Appreciate

indigo orchid
#

How much can a Django application weigh - the basic one created in django admin without changes?

serene prawn
native tide
#

Hi

#

I need a help

indigo orchid
native tide
#

Class Post has not objects member

serene prawn
#

We're talking about python interpreter + dependencies or only the project?

#

@indigo orchid

native tide
#
from django.views import generic
from .models import Post

class PostList(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'index.html'

class PostDetail(generic.DetailView):
    model = Post
    template_name = 'post_detail.html'```
indigo orchid
#

I will describe better what I mean. @serene prawn

long kestrel
#

HI I know how to do many to many between two models but how to do it between three models
`categories_sources = db.Table('categories_sources', db.Model.metadata,
db.Column('categorie_id', db.Integer, db.ForeignKey('categories.id')),
db.Column('source_id', db.Integer, db.ForeignKey('sources.id'))
)

class Sources(db.Model,UserMixin):
tablename = "sources"

id = db.Column(db.Integer, primary_key=True, autoincrement=True)
source = db.Column(db.String(200), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
#catgeorie_id =  db.Column(db.Integer, db.ForeignKey('categories.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
categories = db.relationship('Categories', secondary=categories_sources, lazy='subquery',
    backref=db.backref('pages', lazy=True))
def serialize(self):
    return {'id': self.id,
            'source': self.source,
            'user_id': self.user_id,
            'date_created': self.date_created,
   }

class Categories(db.Model,UserMixin):
tablename = "categories"
table_args = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String(200), nullable=False)
#source_id = db.Column(db.Integer, db.ForeignKey('sources.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
keyword = db.relationship('Keywords', backref='categorie', lazy='dynamic')

def serialize(self):
    return {'id': self.id,
            'categorie': self.category,
            'date_created': self.date_created,
             }

s = Sources()
c = Categories()
c.categories.append(s)
db.session.add(c)
db.session.commit()`

#

it is already done many to many between sources and categories models
but I have other model keywords
with a relation between the two other models
the above models sources and categories

`class Keywords(db.Model,UserMixin):
tablename = "keywords"

id = db.Column(db.Integer, primary_key=True)

keyword = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)


def serialize(self):
    return {'id': self.id,
            'keyword': self.word,
 
            'date_created': self.date_created,

            }`

Please help, thxx!

indigo orchid
#

it is a project (as an example) that has:

  • PostgreSQL with 200 lines (email, nickname and password - fields)
  • DjangoRESTFramework CRUD with around 10 queries (GET
    POST etc)
  • Swagger documentation
  • some tests

rather, without the python interpreter, but with dependencies @serene prawn

serene prawn
indigo orchid
#

yes, entries

long kestrel
#

I found this but not so clear

#

I work with flask

#

flaskrest

serene prawn
serene prawn
#

For just django and it's dependencies it's ~40mb

indigo orchid
#

thanks for the help πŸ˜‰

serene prawn
#

Again - that might depend on your database

#

But it shouldn't be too big πŸ˜‰

native tide
#
@app.route('/test', methods=['GET', 'POST'])
def download():
    return send_file('modules/file_upload/piano2.wav')

what kind of immediate security issues does this type of usage expose?

serene prawn
#

@native tide Perhaps it's that this route is available for everyone πŸ˜‰

native tide
#

just realized i copied and pasted the inverse of this lol one sec

#
@app.route('/upload', methods = ['POST', 'GET'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        f.save(secure_filename(f.filename))
        return "File/s saved successfully. You may close this window."

this is what I was supposed to paste sorry. @serene prawn

#

apart from basic things like file type filtering

serene prawn
#

Uploads should be only use POST method, not because of security, it's just a convention i guess
You didn't really check for filesize/ if file with that name already exists

#

Or for file type

native tide
#

Help me pls

#

yep, i haven't checked for file size or extension yet, but apart from those things what security risks does it pose? the file types expected are non executable

native tide
#

sure

#

how do you render the message in this way?

serene prawn
#

@native tide Again, you didn't check if file with such name already exists

native tide
#

as a piece of code

#

@native tide

native tide
serene prawn
#

I don't really know then πŸ˜‰ I'm not very experienced in security

native tide
native tide
serene prawn
#

!code

native tide
#

thanks

#

How long I should wait?

#

!code

#

My code not works

gloomy edge
#

πŸ˜†

native tide
#

stop it

upper bronze
#

i am trying to get the data from https://www.worldometers.info/coronavirus in a json format but i don't know how to do that...
Please help!!!!!

opaque rivet
#

hey@wooden ruin, sorry for the ping but I thought you'd have some insight into this (if you don't mind):

How can I go about changing a user's group within a channel layer? Let's say I accept a websocket connection for a user, and they connect to the waiting-room group. I now need to move them to the chat1 group. Then, I need to move them to the chat2 group.

However the issue I'm facing is that I cannot track which group the user is in. Any way to go about this? Do I use a database for this?

polar trellis
#

something like this should get you started

gloomy edge
#

whats this

upper bronze
polar trellis
#

check the edit

upper bronze
#

ok

upper bronze
polar trellis
#

swap it with html

#

i amde some typos i put it together quickly

upper bronze
#

oke it worked as expected

inland copper
#

see my website

upper bronze
#

link?

inland copper
#

sorry not that

#

this one

#

hope u like it @upper bronze

upper bronze
#

nice

upper bronze
polar trellis
#

since the output is a pandas dataframe you can do with it what you want it is very flexible just lookup the pandas docs

upper bronze
#

oke thanks!

native tide
#

Anyone know how to get gevent working with selenium? I am getting a WebExceptionError SSL Protocol error (even after ignoring certificates and other SSL stuff)

quasi relic
#

guys what do you recommend for backend with python , what should I learn after flask ?

native tide
#

jinja maybe

cedar pasture
#
curr_date = pd.to_datetime(list1[-1])
        for i in range(X_FUTURE):
            curr_date = curr_date +  relativedelta(months=+1)
            dicts.append({'Predictions': transform[i], "Month": curr_date})
            

        new_data = pd.DataFrame(dicts).set_index("Month")
        ##df_predict = pd.DataFrame(transform, columns=["predicted value"])

        new_data.to_csv(os.path.join("downloads", index = True, encoding='utf8'))

        labels = [d['Month'] for d in dicts]
            
        values = [d['Predictions'] for d in dicts]

        colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                       "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                       "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]

        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values, filename = filename)

@app.route('/download/<filename>')
def download(filename):
    return send_from_directory("downloads", filename, as_attachment = True)
cedar pasture
#

HTML > >><a href="{{ url_for('download', filename=filename) }}">Download</a>
Hi community, I m trying to save my to_csv into os.path.join and return the csv file from download button in HTML page, currently I m getting this error TypeError: join() got an unexpected keyword argument 'index', Does anyone excel in flask python, please correct me ~ Appreciate

quasi relic
#

I mean that what would be important after flask framework on my journey

tribal pewter
#

start building projects

quasi relic
#

so just jump into any kind of project...

#

good point no better way to learn

gritty moth
#

someone help

#

it's pretty easy

#

using flask

errant spear
#

If I have an issue with flask cors should I ask here or in a help channel?

dapper tusk
#

here is probably better

#

if something fits into a topical channel, it tends to be the better place

upper bronze
# polar trellis ``` import pandas as pd import re import requests html = requests.get('https://w...

with the help of your code, i am able to make this:

import pandas as pd
import re
import requests
html = requests.get('https://www.worldometers.info/coronavirus/').text
html = re.sub(r'<.*?>', lambda g: g.group(0).upper(), html)
df = pd.read_html(html)
js = df[0].to_json()   
js = json.loads(js)   
fil = open("file.json","w")
json.dump(js, fil, indent=4) 

def add(text):
    with open("cases.txt","a+") as f:
        f.write(text)

add("---------------------------------------\nWORLD \n--------------------------------\n")
add(f'{js["Country,Other"]["7"]}: \nTotal cases:{js["TotalCases"]["7"]} \nActive Cases:{js["ActiveCases"]["7"]} \nTotal Deaths: {js["TotalDeaths"]["7"]} \nTotal Recovered: {js["TotalRecovered"]["7"]}\n')
add("--------------------------------------- \nCONTINENTS \n------------------------------\n")
for i in range(5):
    add(f'{js["Country,Other"][str(i+1)]}: \nTotal cases:{js["TotalCases"][str(i+1)]} \nActive Cases:{js["ActiveCases"][str(i+1)]} \nTotal Deaths: {js["TotalDeaths"][str(i+1)]} \nTotal Recovered: {js["TotalRecovered"][str(i+1)]}\n')
add("--------------------------------------- \nTOP 3 COUNTRIES \n--------------------------------\n")
for i in range(100):
    add(f'{js["Country,Other"][str(i+8)]}: \nTotal cases:{js["TotalCases"][str(i+8)]} \nActive Cases:{js["ActiveCases"][str(i+8)]} \nTotal Deaths: {js["TotalDeaths"][str(i+8)]} \nTotal Recovered: {js["TotalRecovered"][str(i+8)]}\n\n')```
#

thank you very much!!

naive venture
#

Hey, I'm looking for someone with experience in django. I have a deployment problem with the CSRF cookie

daring cairn
#

anyone knowledgeable on flask/html wanna hop on a voice call. I need some help with implementing flask class please

long kestrel
grim tiger
#

@swift wren For the reminder service, I want to support SMS and email.

buoyant shuttle
#

hey guys i need help

swift wren
#

feel like thats gonna be some paid services

buoyant shuttle
#

im getting this type of error

Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <?xml version="1.0" encoding="utf-8"?>
``` trying to load svg image in react, in my django server
swift wren
#

javascript error

#

doesnt apply to django

buoyant shuttle
#

i know

swift wren
#

unless its a path error

buoyant shuttle
#

how do i get loader app, i set up react manually, since im using python djangos server not a node server

swift wren
#

also

buoyant shuttle
#

uhm ok thxs

#

i have like 150 servers jeez

swift wren
#

This django and react tutorial covers how to integrate react with django and perform all of the necessary setup steps. We will be using webpack and babel to bundle our react app and have the django backend render a template that react will control.

πŸ’» AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify i...

β–Ά Play video
buoyant shuttle
#

ive watched the entire series

#

he doesnt use images via react, the images he uses are static from django

swift wren
#

then thats because django handles the static files

#

also svgs are bad and require to be handled by js

#

use pngs

buoyant shuttle
#

its a loading pic

swift wren
#

convert it and its going to save you alot of headache

buoyant shuttle
#

its used, to get user attention while making http request

#

uhm ok

swift wren
#

have you used django without react?

buoyant shuttle
#

yes

#

django and pure js

swift wren
#

did you make a serizliser?

#

i wanted to learn how to use react with serialzer but i found it hard

buoyant shuttle
#

yeah my API endpoints are working

#

ah

swift wren
#

what are end points

#

are they like the output of the api data transfer?

buoyant shuttle
#

url routing. endpoitns is what i use for API.

#

i read a blog about it, and tbh tims video is also based off that blog

swift wren
#

api routing? isnt a api used for data

buoyant shuttle
#

also had to read abour django restframework first.

swift wren
#

i said fuck off to the serializer and stuck to straight up html

buoyant shuttle
#

for example. lets say i have a route. /api/data. in my website its www.website/api/data.
using pure django i can set the urls and the correspondent views. the view that hanles the ui rendering or content. Like homepage, about page etc

#

its basically just a page with json

naive venture
#

@buoyant shuttle seems like you know about SPAs, have you worked with csrf cookies?

wooden ruin
swift wren
#

yeah ofc

#

properly get the whole system working with static dirs

wooden ruin
#

yep, its best to use things like staticdirs than hardcoding each link tbh

opaque rivet
#

for django channels is it best to have one group per consumer, or multiple groups per consumer?

wooden ruin
opaque rivet
# wooden ruin typically you would want multiple consumers per group

hmmm... what I'm doing now is having a client connect to something like ws://mysite:8000/<str:query_param>/, then connecting the channel to a group based off the query param.

But the user can change this query param and I want to change its group based off that. How should I do that?

I have 2 ideas:

  • Make one consumer for each possible query param so there's one group per consumer.
  • Make one consumer, and pass that query param via JSON, and have a database recording which group a channel is in.

I think the 2nd option is what most people do when they want to allow a channel to change groups, right?

wooden ruin
opaque rivet
#

yeah I don't think it's scalable (the 1st option), I can have 10 urls each with a seperate consumer and the client connecting/disconnecting between them

opaque rivet
wooden ruin
opaque rivet
ember skiff
#

Can I make dynamic websites using flask?

stable hemlock
opaque rivet
#

anyone made custom django middleware? why do you need a middleware factory (and not just a middleware function)?

native tide
#

why did netlify gave me "build.command" failed? ping if you want to help me

pearl birch
#

I am making a Django Blog website. I want to keep a list of authors the user has subscribed to. anyway to do this? Thanks!

vestal dove
#

Am I able to host a flask website publicly?

echo hound
vestal dove
lavish prismBOT
#

:x: According to my records, this user already has a mute infraction. See infraction #31157.

#

:incoming_envelope: :ok_hand: applied mute to @wintry delta until 2021-04-06 23:28 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

ashen sparrow
#

In django, if I want to have a field in my model where I store the related objects (for suggestions) how do I need to implement the manyToMany Relation?

native root
#

Does field_name = models.ManyToManyField(Class) not work?

pearl birch
#

thank you

broken talon
#

for some reason, authenticate() is not working when i use a custom model

#

i even changed AUTH_USER_MODEL in settings to my custom user model

#

can anyone explain how i can fix this?

ocean tide
#

I'm trying to get the cartoon image to come half way out of the grey box. Is there a way to use negative padding or something else?

cold schooner
#

negative margin?

ocean tide
#

when I use that the entire box moves up

#

not just the picture @cold schooner

cold schooner
#

negative margin-top ought to be able to push it outside the container, as long as it's applied directly to the image.

ocean tide
#

thx

surreal grail
#

anyone familiar with Django Rest Framework?

#

Particularly authentication, bit confused on how it works confused to normal Django session auth
So I just need to provide an endpoint to submit username and password - ???
then the cookie will be saved and I can get the instance of the User object for each request
(I put more question marks next to the confusing bits)

serene prawn
#

There was a page about auth on drf website

surreal grail
#

My goal is to create a custom login page, because I'm using react as the frontend, maybe I'm missing something

#

Where do you actually send the username and password to be authenticated?

#

Sorry for the spam, thank you

grand oriole
#

does anyone here know anything about the patreon API and could help me?

wooden ruin
#

because if so you will have to manually configure the session cookies so logging in actually logs you in

unique stirrup
#

hey, i wanna get certain paragraph on a webpage(s) using bs4, the problem is, it (the <p> tag) is not attached to anything with which i can fine-tune my find function and there are a lot of <p> tags with same name (of <p>), i want a robust solution for this problem because, i am doing it for multiple webpages (and they are quite inconsistent),soo what can be done?

Fixed it, ^^

hallow knot
#

does anyone have a recommendation when it comes to scheduling task for a django webapp? I tried dj-crontab and django-crontab (which are basically the same), but they dont seem to work reliable. I set two task up as described in the documents, but it seemed pretty random if they were actually executed. At first the first task wasnt running, but the second did, so i deleted the first one, then the second one didnt get executed aswell. No error messages, and it showed up with crontab list

opaque rivet
spare sphinx
hallow knot
#

perfect, thank you guys

opal portal
#

i have problems with django and django rest framework, i would be very grateful if anyone is free right now and can discuss and help me with code. i tried google and stackoverflow but i couldnt find a solution (probably because of my bad english)

opal portal
#

@@ it's some problems with drf and abstract models. it would be easier to explain with code but my neighborhood just black out. i guess i come back later in the morning

sweet wharf
#

I have a quick question about flask. I am trying to use app.config["APPLICATION_ROOT"] = "/api/v1"as a prefix for all routes, but it does not work. Anyone have any suggestions.

I know I can use f strings for a prefix but I rather have it like this if it's possible

tough briar
#

is there a way to track flask endpoint calls with custom options?
for example theres "premade/thing/<typesomething>"
and i want to keep track of the type something like

"premade/thing/typesomething":{
"pee":3,
"poo":5
}

thats just an vizulazation, can be completely different, but like in general is there a way to track it

leaden perch
#

convert = soup.find_all('span', {'class': 'DFlfde','class': 'SwHCTb', 'data-permissions'})

#

who knows why the error

white spruce
#
<div class="recipe">
        <p id = "recipe-header" style="text-align: center;">Creating a Recipe</p>
        <form>
            <div style="background-color:#D3D3D3;" class="recipebox">
                <div class="recipecol">
                    <p> Select Ingredients</p>
                    <select name="ingredients" class="ingredient"> 
                        {% for measurement in measurements%}
                        <option value="{{measurement['Quantity']}}">{{measurement['Quantity']}}</option>  
                    {% endfor%}
                </select>
                    <select name="ingredients" class="ingredient"> 
                        {% for ingredient in ingredients%}
                        <option value="{{ingredient['IName']}}">{{ingredient['IName']}}</option>  
                    {% endfor%}
                </select>
                </div>
                <p> Add Instructions for Recipe</p>
                <div class="recipecol"> 
                    <textarea name="instruction" rows="15" cols="40" placeholder="Enter instructions for Recipe"> </textarea>  
                </div>

            </div>
        </form>
    </div>

I want to center this form, two columns. One for ingredient and other for instructions. Any guide
my css so far

#recipe-header {
    font-weight: bold;
    font-size: 26px;
}

.recipebox {
    margin: auto;
    display: table;
    clear: both;
}

.recipecol {
    float: left;
    width: 40%;
    padding: 10px;
}
#

hey Kala, are you good with css can help?

real hare
#

Hey Der, can you stick that into a codepen or something similar? Then I can have a look

white spruce
#

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

white spruce
#

sure

#

thank you man, appreciate that, setting it up now

real hare
#

Np

white spruce
real hare
#

Cool, thanks having a look now

white spruce
#

Awesome, ty

real hare
#

I'd do the following:

  • Create a parent div, put something like:
display: flex;
justify-content: space-between;

Then put the two divs inside, and unstyle them it should do the trick

#

<div class="recipe-col-parent">
<div> </div>
<div> </div>
</div>

white spruce
#

look at it, I got a parent div called recipe

#

can't you edit the css?

sharp jungle
native tide
#

what is the best module to make a browser

white spruce
#

@real hare could you edit the css

livid mural
#

Django
Hey guys, I am working on social media site and I dont have idea how to connect post made by user to his place in database, can someone help please?

real hare
#

Please follow the steps provided that should get you into the right direction

serene prawn
#

Anyone can help me with FastAPI + Mypy?
I'm using dependency injection in my routes and mypy is saying that Default for argument "profile" (default has type "Depends", argument has type "Profile")

profile: Profile = Depends(profile_manager.with_profile),

despite that with_profile returns Profile object

Same happens with Cookie, Body and Query parameters

signal bronze
#

I want to do something like this to get the username in flask. How can i achieve this?

@app.route('/u/<string:username>', methods=['POST', 'GET'])
def userpage():
    username=request.args.get('username')```
serene prawn
#

@signal bronze

@app.route('/u/<string:username>', methods=['POST', 'GET'])
def userpage(username: str):
    username=request.args.get('username')
signal bronze
#

Thanks

native tide
#

Need help dm me

signal bronze
signal bronze
serene prawn
#

delete username=request.args.get('username')

signal bronze
#

Oh

#

thanks!

serene prawn
#

your username argument will be passed into a function

native tide
#

hello , can someone help me?

signal bronze
native tide
#

the code?

#

oh

#

am i made a website with flask and when i runned it it says no module named website but i installed the module already

#

@signal bronze

signal bronze
#

what ide are you using?

native tide
#

vscode

#

and i use conda 8.3

#

on mac sierra

signal bronze
#

your not on windows?

native tide
#

no i bought this macbook today

#

i was on windows

signal bronze
#

i am unable to help further

native tide
#

oh ok

#

but how to could i do it

#

because this site was for my mom she wants to sell cakes

marble gate
#

Hello how can I send a public key , private key and username through a request in python

Like this

curl -u username --key "privatekey.pem" --cert "cert.cer" --cert-type PEM

native tide
#

ok but i still wanna know why this happens

swift sorrel
#

Hi, why do I always have this error while I'm running my django web server ?

The error :

ConnectionAbortedError: [WinError 10053]
swift sorrel
#

bruh

opaque rivet
#

that error is not framework-specific.

opaque rivet
#

we need more information about your error to diagnose your error.

opaque rivet
native tide
#

this happens when i run my web server

opaque rivet
#

well, yes - because where is the website module?

native tide
#

i installed it alreasy

#

already

opaque rivet
#

I don't use Flask, but either website is not a real module or you have the wrong path to something. Do pip list and you'll see your dependancies.
Also I don't think you're going the right way about settings up a Flask app, it should be something similar to this:

from flask import Flask
app = Flask(__name__)

then in terminal

$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask run```
opaque rivet
opaque rivet
native tide
#

oh

#

wait i am gonna post a screenshot of my pip list ok?

opaque rivet
#

I gave you the solution - my question to you is why are you doing from website import create_app

native tide
#

i watch a video from tim

#

and did what he did

#

wait ill send link

opaque rivet
#

i don't need the link. website is not a valid module (it's not found in pypi). You are better off reading official docs

native tide
#

In this video, I'm going to be showing you how to make a website with Python, covering Flask, authentication, databases, and more. The goal of this video is to give you what you need to make a finished product that you can tweak, and turn into anything you like. We're going to also go over how you create a new user's account, how you store those...

β–Ά Play video
opaque rivet
#

what?

native tide
#

i do not check it

opaque rivet
#

so... maybe check out the docs then?

#

I gave you a solution above

#

but it's good if you understand the solution rather than just copying the code

native tide
#

link to the docs?

thorn igloo
# native tide link to the docs?

if you're using blueprints, 'website' should be the name of the folder where you have the init.py file with the create_app function

thorn igloo
#

if you see here, the guy has a folder called website, that's why it works for him,

native tide
thorn igloo
native tide
thorn igloo
#

in website mamma?

native tide
#

my website folder is called website mamma

#

yes

thorn igloo
#

rename it to like website

native tide
#

ok

#

how can i rename on mac? i bought this macbook today

thorn igloo
#

normally it's right click and rename, but i'm not sure how it's done on mac

native tide
#

yea doesnt work with right click wait iam loocking up

#

ok did it

thorn igloo
#

alright

native tide
#

now

#

its says no flask but i hav it already installed lol

thorn igloo
#

hmm

#

pip3 install flask should fix it

native tide
#

ok wait

#

wrong screen shot

#

😦

thorn igloo
thorn igloo
opaque rivet
#

error with postgres, can anyone help?
django.db.utils.OperationalError: FATAL: database "db" does not exist

# settings.py
DATABASES = {

    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'localhost',
        'PORT': '5432',
    }

}

But, I do actually have a database created with pgAdmin called db.

native tide
#

@thorn igloo yea i am in my python directory there is my main.py file and the website stuff

thorn igloo
native tide
#

i use python 3.8 python3

thorn igloo
#

let me know what it says

native tide
#

what?

#

idk what you mean

thorn igloo
#

python3 -m venv venv run this in the terminal

native tide
#

oh thanks

#

it worked

#

i love you (no homo)

#

thank you so much

thorn igloo
#

your code runs now?

native tide
#

yes baby

thorn igloo
#

alright

exotic gale
#

Not sure if this is the right place to ask this but here goes anyway. I have a website and app which interacts with a Python package/few functions which are files through a flask restful API I built. It's just being hosted on my laptop atm as everything is still in development stage. Now where is a good place for me "host" my python code? I basically just want something thats going to be fast and fairly cheap and easy for me to setup, maintain and make changes to my code. Also my code runs at about 20 seconds each time atm so I am planning on perhaps implementing multiprocessing so the hosting platform would need to support that. If anyone has any experience or ideas that would be great. Thanks

lime fox
#

yo if anyone has any experience with using php please @ me or message me asap

covert bloom
#

anyone know how to set up flask-mail? I do not get it πŸ˜‚

#

ping me

lavish prismBOT
sly canyon
#

@covert bloom I've used it before, I may be able to help

#

There's a good tutorial though from Miguel Grinberg

covert bloom
#

yee, they're good

opaque rivet
#

anyone used postgres w/ django? ever had an issue where you do makemigrations but the database schema isn't updating? I've been stuck on this all day

#

somehow need to understand migration files 🀦

maiden tulip
#

Hi, just started in react and found this line in index.html

    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

And I wonder why it is called logo192. I guess it means 192x192px, but why exactly 192? is this some kind of apple touch icon standard? SO post said to use 180x180 px for apple icon and 192x192 for android
(please ping me)

analog gust
#

From all that I have seen there is not good tutorials out there for updating a flask webpage without refreshing using AJAX could someone help me in #help-carrot ?

gloomy ginkgo
#

Flask vs. Django

#

Personally I like Flask

sly canyon
maiden tulip
opal portal
#

if a have a model like this
class ModelA(models.Model): file = models.FileField(upload_to='media/')
and i want to store uploaded files in different locations based on the file type such as jpg,png into media/images and doc,docx,pdf into media/documents

#

how can i achive this

hoary sand
#

.topic

fallow cairnBOT
#
**What tools do you use for web development?**

Suggest more topics here!

worldly garden
#

I use DRF and try to create a user, but I have an error "email": "This field is required." I don't know how to fix this, can anyone help with problem?

### Models ###    
class User(models.Model):
    full_name = models.CharField(max_length=255) 
    password = models.CharField(max_length=255)
    birth_date = models.DateField(blank=True, null=True)
    contacts_number = models.PositiveIntegerField(default=0)
    creation_date = models.DateField(auto_now_add=True) 

    def str(self):
        return self.full_name

class Email(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email = models.EmailField(unique=True)
    is_activated = models.BooleanField(default=False)
    last_modified = models.DateTimeField(auto_now=True)

    def str(self):
        return self.name

### Serializers ###
class EmailListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Email
        fields = ['email']

class RegistrationSerializer(serializers.ModelSerializer):
    email = EmailListSerializer(write_only=True)

    class Meta:
        model = User
        fields = ['id', 'full_name', 'password', 'email']

    def create(self, validated_data):
        received_email = validated_data.pop('email')
        print(received_email)
        email = User.objects.create(**validated_data)
        print(email)
        return email
vestal hound
#

do you know what .pop does?

frigid fiber
#

what is the best way to build the realtime stock dashboard with django? to use webhook? or frequently request the api?

frigid fiber
#

Does Django has api for setting up with webwook?

frigid fiber
signal bronze
#

with flask_sqlalchemy can i create another table in a class.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), nullable=False, unique=True)
    email = db.Column(db.String, nullable=False, unique=True)
    password = db.Column(db.String, nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    still_active = db.Column(db.Boolean, default=True)
    admin = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return '<Task %r>' % self.id
        
    class PostsCreated(db.Model):
        post_count = db.Column(db.Integer(), primary_key=True)
        link = db.Column(db.String, nullable=False)``` like that?
wispy quail
#

Great idea though ^^

#

Btw web folks check out this project: Allows you to use Django features in Flask: https://github.com/Abdur-rahmaanJ/shopyo

GitHub

🎁 Your Open web framework, designed with big in mind. Flask with Django advantages. Build your management systems, ERP products & mobile backend (coming soon). Small business needs apps inc...

#

At this stage i need feedbacks. Ping me here or open an issue. Much much appreciated

#

By feedback i mean just run the project and see what rings fake with the experience

wispy quail
wispy quail
#

Today discovered the Web Dev channel. I sense that i might be able to give some Flask help ^^

wispy quail
wispy quail
#

Ah ok!

covert bloom
#

but I will look into flask mail man, thank you

opal portal
#

so is there a way to do so with django ?

frigid fiber
opaque rivet
# frigid fiber Can you explain why?

websockets allows the server to communicate directly with the client, instead of having to have the client initiate a request to the server and await a server response like a usual api.

#

@frigid fiber I'm also using them for a realtime stock dashboard

frigid fiber
opaque rivet
#

if u got more qs then just put em here

twilit thorn
#

im trying to map a url and under url patterns i wrote path('', views.index, name='index'),
] but it gives me an error which says AttributeError: module 'learning_logs.views' has no attribute 'index' can anyone help?

frozen abyss
twilit thorn
#

yep

frozen abyss
#

And have you defined the index function in views.py?

twilit thorn
#

wdym?

frozen abyss
#

Could you show us the code in views.py?

twilit thorn
#

def index(request):
'''the home page for learning log'''
return render(request, 'learning_logs/index.html')

#

i wrote that

frozen abyss
#

Could you paste all the code for views.py please?

#

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

twilit thorn
frozen abyss
#

Have you got any imports in views.py?

twilit thorn
#

yeah

frozen abyss
#

Could you paste those too?

twilit thorn
frozen abyss
#

Is that from views.py? That looks like it's from urls.py

twilit thorn
#

oh yeah whoops xD

#

from django.shortcuts import render

frozen abyss
#

Ok that makes sense

#

I think in urls.py you need to import the view

native tide
#

what does models.ForeignKey() do?

frozen abyss
#

from learning_logs import views

#

@twilit thorn

frozen abyss
twilit thorn
frozen abyss
frozen abyss
twilit thorn
#

wow thanks

frozen abyss
twilit thorn
#

yep : )

frozen abyss
#

Nice!

sharp jungle
#

Is it possible to change the style of a specific object using flask?

graceful veldt
#

can anyone help me in django

frozen abyss
#

Ask away!

frozen abyss
wispy quail
sharp jungle
#

Nvm I got it, I used style in the tag, it was an h2 object

wispy quail
#

oh i'd expect the word tag

graceful veldt
#

actually I am building an ecommerce site and i need make a popup form apper for some special product

#

@frozen abyss i am adding an feature to the site which make it easier for the product to stock if its gone finish in your home.. for this if the product is listed as prescribed then a form should popup and then the information in the form will be used to calcuate a time to sent a web push notification to the user.

frozen abyss
frozen abyss
frozen abyss
graceful veldt
#

@frozen abyss can you help now

frank lake
#

hello guys, can you recommend me any address validation api or library? It would be really nice if it is working with django form

frozen abyss
frozen abyss
graceful veldt
#

@frozen abyss no just help with some related stuff

#

I can use your knowledge , notification i will do i my self using js

frozen abyss
graceful veldt
#

@frozen abyss code /help 1

frozen abyss
distant charm
#

is there a way in Flask to stop direct access to routes. like only render template if redirected to the routes

wispy quail
distant charm
#

i just need to create a small presentation lol

elder nest
#

can someone help me on how to update a mongodb database through a quart webpage update button

#

like this

#

I already connect to get the settings to appear in the box but I dont know how to update it from the html file

pearl bay
#

Hi guys

#

How do we add ids to a django form

frozen abyss
#

<div id="">{{ form.username.label1 }}</div>

frozen abyss
whole osprey
#

Hey anyone know how to manage proxies on selenium?

frozen abyss
wispy quail
#

ingenious solution ^^

native tide
#

Hey guys..

#

Does anyone uses flask

surreal thicket
wispy quail
worldly garden
limber laurel
#

are there any advantages of token auth over sessions?

rain knoll
#

I'm writing Jinja templates in vscode, and for some reason whenever I write a statement, like {% ... %} on a single line, and press enter, it auto-changes to % ... % (It removes the curly braces). Does anyone know why, and how I can turn off this behaviour?

thorn igloo
ocean dirge
#

can anybody tell me why there is a large area above my header div?

#
html {
    padding: 0;
    margin: 0;
    height: 100%;
}
body {
    padding: 0;
    margin: 0;
    height: 100%;
    background-color: #aca1a1;
}

header {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 10%;
    background-color: rgb(68, 68, 68);
}
header .company {
    height: 100%;
    width: 20%;
    font-size: 32px;
}
#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="description" content="Website for my raspberry pi">
    <title>Samirs Raspberry Pi Ui</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="resources/index.css">
</head>
<body class="nice">
    <header>
        <div class="company">
            <p>PiGui</p>
        </div>
    </header>
</body>
</html>
#

without the company class the header aligns to the top without issue

#

fixed, needed inline block

stable hemlock
#

How do I redirect a user back to their original destination after an oauth2 login? For example, I have a /subscribe page that requires user login, so if a user is not logged in they get sent to the oauth login page, and then after I want them to go back to the /subscribe page. (This also applies to several other pages on the site)

elder nest
#

how would I make a save button in html that updates a mongodb database with text entries in the html

#

im using quart

maiden tulip
wispy quail
wispy quail
elder nest
mint folio
#

The oauth server should redirect you back to your app

wispy quail
stable hemlock
mint folio
#

You need a endpoint in your app for callback, which you give the oauth to redirect back to

wispy quail
#

Clicking on a button will send inputs to the endpoint where you catch then add to the db

stable hemlock
mint folio
#

Yeah

stable hemlock
# mint folio Yeah

Can you point me to an example? I don't know where in the oauth2 uri to put the redirect.

elder nest
#

@wispy quail is there a way I can make it so there is a hidden thing that the form gets

#

when it submits

elder nest
#

nvm I figured it out

#

I was trying to have the user code and the guild id hidden

#

so the user couldnt change it

#

but it still got picked up by the form

#

@mint folio I have a question bc you seem to know how to use oauth. How would I see if a user has a specific permission

mint folio
#

The user can always change data on the frontend, which is why you should always validate in the backend.

elder nest
#

like administrator or manage server

mint folio
elder nest
#

like in a discord server

#

to see if they have admin in a server with a specific id

mint folio
#

When you authenticate the user with discord they will give you an token which you can use to make requests to discord on users behalf

elder nest
#

I already have that

#

I have the whole dashboard working other than everyone can change everything

#

what request would I need to make to see what perms they have

mint folio
#

I don’t use discord api, I’m not sure

#

Have you tried finding it in their docs?

elder nest
#

yes

#

I did ctrl f permission

#

and looked through the permissions

#

but couldnt find anything

mint folio
stable hemlock
elder nest
#

Yes I understand that but if I have the permission numbers I can just check for the admin permission number

#

Or tha manage server permission number

#

Idk which one I’m doing yet

opaque rivet
#

wooh, just fully transferred to linux

#

feeling good

elder nest
#

how would I make it so the user can't change the text in this box <input type="text" id="prefix" name="prefix" value={{ prefix }}><br><br>

stuck glen
#

Hello

#

I want to learn web dev with py

#

:thumbsup:

opaque rivet
native tide
#

Does anyone have a good source to help me start web development, for my anti-nuke??

stable ledge
wispy quail
#

?

wispy quail
native tide
#

I jsjt@need something basic

elder nest
#

but I am just making it so it cant be changed

hollow night
#

do I even need web framework?

#

my server has 4 endpoints

#

2 for ML model, 1 for getting the result(db), 1 for submitting feedback(db)

#

Should I just serve them via uwsgi?

swift wren
#

hey if anyone is on i had a question
i have a linux laptop and a windows 10 computer
if my laptop sshs into my computer and runs a flask server, will my computer be able to develop on that server or will my laptop be limited to the server only
is there a way where i can have my windows 10 server running on a linux laptop and edit my files on my windows 10 computer?

stable ledge
supple bramble
#

yo can someone give me some good reasons to use Django over NodeJS,

I wanna win against my js addict friend with my django love (python in general)

supple bramble
#

I saw it

#

HAHA

#

database yup that's a reason I have in mind, but want something better to support my choice

tribal pewter
#

Easier, more secure

#

but yeah there is no point for that argument in the first place

#

everyone uses whatever they like, feel comfortable with πŸ™‚

supple bramble
#

the thing is that we both are comfortable with with both but I'm a bit biased towards django (python on general)

#

and he is with nodeJS

native tide
#

I didn't study Js, is js hard to learn?

supple bramble
#

hahaha

supple bramble
#

but in this comparison (NodeJs vs Django) I think django is much easier and straight to point

#

and because it's python, you can do literally anything

wispy quail
#

Like how you called it now flask has no idea what request was being addressed

wispy quail
distant charm
#

So my flask app is not recognizing my css files and i have no idea why

#
<link href="/static/css/404.css" rel="stylesheet">```
mint folio
#

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

distant charm
native tide
swift wren
#

oh i did it

#

it fully works, its so cool. i can develop on both my laptop and pc

native tide
green snow
#

Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 11, in main
from django.core.management import execute_from_command_line
File "C:\Users\GKMSHIPPING\Envs\testyy\lib\site-packages\django_init_.py", line 1, in <module>
from django.utils.version import get_version
ValueError: source code string cannot contain null bytes

#

i got this when i tried python manage.py runserver

distant charm
swift wren
#

dont use envs

#

with django

#

if you are then use conda

green snow
#

the thing i have built my uni project on this

#

so how do i fix this

dusky vault
#
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
        {% for post in posts %}
          <div class="post-preview">
            <a href="{{ url_for('post', post_id=post.id) }}">
              <h2 class="post-title">
                {{ post.title }}
              </h2>
              <h3 class="post-subtitle">
                {{ post.subtitle }}
              </h3>
            </a>
            <p class="post-meta">Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}</p>
          </div>

            {% if post == posts[-1]  %}
              <br />
            {% else %}
              <hr />
          {% endfor %}

hi im making a web application on flask and this is the snippet of my code to the articles template I have a sqlite database that contains the articles, how can I make an if statement that detects if the post is the last in the loop since im making an hr per article {% if post == posts[-1] %} doesn't seem to work

glacial sandal
#

flask question :

#

css is not being applied

#
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Major Chat</title>
   <link rel="stylesheet" href="G:\My Drive\Chat app\static\style.css">
   <link rel="stylesheet" href="G:\My Drive\Chat app\static\bootstrap.min.css">
</head>
<body class = "text-center">
   <form class="form-signin" action="{{url_for('chat')}}" method = 'post'>
      <h1 class = 'mb-3 font-weight-normal'>Major Chat</h1>
      <input type="text" id = "username" name="username" class='form-control' placeholder="Username" required autofocus>
      <br>
      <input type="text" id='room' name="room" class='form-control' placeholder='Room' required>
      <br>
      <button class = 'btn btn-lg btn-primary btn-block' value="submit"><b>Start Chatting!</b></button>
   </form>
</body>
</html>``` 
this is the code
native tide
#

in detail views

glacial sandal
#

i did

native tide
#

you did not load it

glacial sandal
#

??

native tide
#

{% load 'static' %}

glacial sandal
#

where should i do that??

#

in html file??

native tide
#

yep above the doctype

glacial sandal
#

k

native tide
#

and also paste this in your settings

#
    os.path.join(BASE_DIR, 'static')
]```
#

so it can find the css files

glacial sandal
#

umm...

#

its flask

#

not django

native tide
#

sorry men

glacial sandal
#

k

#

np

native tide
wispy quail
#

normally you'd do if posts[index+1] is None but since loop.index is already incremented, just use it as such

wispy quail
wispy quail
wispy quail
pearl bay
#

Hi guys can anyone join the vc and help me with styling django forms

native tide
#

easy style

opaque rivet
#

trying to access models within my channels consumer:

group = await database_sync_to_async(Groups.objects.get_or_create(name=f"{content['selectedEquity']}-intraday"))()
                channel = await database_sync_to_async(Channels.objects.get_or_create(name=self.channel_name, group=group))()

getting this error:
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

But I am using sync_to_async?

quick cargo
#

its because you're directly calling the function which will immediately call the function instead of actually running it in a thread

opaque rivet
#

sorted it like this

#
group, created = await database_sync_to_async(functools.partial(self.get_group, content))()
#

thanks πŸ™‚

quick cargo
#

πŸ‘Œ

stable ledge
native tide
#

Maybe someone will take advantage of this:
Great opportunity, Cisco International announced the launch of five (free) remote training programs

Cisco International announced the launch of (5) distance training programs (for free) via

Cisco Virtual Academy, with a total of (245) hours in the following fields:

1- Introduction to Cybersecurity - 15 hours

2- Introduction to the Internet of Things - 20 hours

3- Entrepreneurship - 70 Hours (Entrepreneur)

4- Programming Essentials in Python - 70 hours

5- Linux Essentials - 70 hours

And the beautiful thing is that the application is available to everyone free of charge
Also, training in several languages

https://www.cisco.com/c/m/en_sg/partners/cisco-networking-academy/index.html

native tide
#

any help that i can get? why is there errno 48 already in use wtf

wispy quail
#

try passing port=5001 in app.run(...)

brisk spear
#

Hey

#

What shall I start flask or django ?

stable hemlock
brisk spear
#

Well any videos u would recommend for learning it ?

stable hemlock
brisk spear
#

Well ok thanks

native tide
wispy quail
brisk spear
#

Well I tried flask

wispy quail
#

^^, quite simple

brisk spear
#

But I got demotivated

wispy quail
#

y?

brisk spear
#

Somethings were not going good

wispy quail
#

how?

brisk spear
#

Well bro how will I learn flask ?

wispy quail
#

Do a project with it. Learn as much as you need ^^

brisk spear
#

If I just watch video and do what is shown in video

wispy quail
#

Like have an idea of your own

brisk spear
#

Okay

wispy quail
#

Lets say a simple todo app

brisk spear
#

Ok

#

Well I just know basics but not backend and all

wispy quail
#

use flask_sqlalchemy

brisk spear
#

Bro u know flak?

wispy quail
#

you can use sqlite, you dont even need a db

wispy quail
brisk spear
#

How much like pro ?

#

How u started pls some advice

wispy quail
#

You can say, i'm one of the organising members of a conference called FlaskCon it seems

wispy quail
brisk spear
#

Ok

wispy quail
# brisk spear Ok

See this FlaskCon interview from someone called Abhishek Kaushik who has a hobby project called creatorlist: https://www.youtube.com/watch?v=OneNCbMrib4 . Not learning for the sake of learning. It's learning to put into practice. To do what you want, you'll come across challenges. To overcome those, you'll learn what you need to learn.

Abishek discovered Flask on a summer internship, and then Creatorlist (https://creatorlist.tech) was born. He shares his journey of how he learnt Flask from scratch and the resources used. While building the platform, how he set up his implementation criteria, server setup and the use of Miguel’s built SocketIO to make the website.

https://flas...

β–Ά Play video
#

In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog

Djang...

β–Ά Play video
#

It's kind of great to go along

#

Ping me with any question you have ^^

brisk spear
#

Ok sure

#

Thanks for help

delicate nest
#

sanic is also good @brisk spear

#

its basically flask but faster

wispy quail
delicate nest
#

not sure

wispy quail
#

well quart is expected to be merged with flask ~

#

as it's a flask experiment

#

it's by a flask maintainer btw

#

right now if someone wants asgi flask, use quart. same code exept in edge cases. basically just change imports

quick cargo
#

pithink Idk where you got the whole merged with flask thing

#

Quart was and is developed completely separately from Flask and will continue to be separate systems

#

Quart is also about the same speed as flask

#

people just dont know how to properly scale Flask to offer as much performance as Quart because Quart forces you to use the systems that make it fast on IO

#

Quart in reality is by far one of, if not the slowest asgi framework around because it goes with the whole trying to mimic flask which was designed to be used with an entirely different event loop and async design

wispy quail
#

@quick cargo you follow the latest flask dev actualities?

quick cargo
#

i do not, no

wispy quail
#

^^

quick cargo
#

I would find it very odd and concerning if flask moved to be quart

wispy quail
#

the pallets server has more conversations on the subject

quick cargo
#

Flask moving to async would break so much stuff and ruin alot of the eco system it built up

wispy quail
#

what do you mean by ruining a lot of the ecosystem?

quick cargo
#

Well Flask's current ecosystem is built around being Synchronous and eventlet / gevent based

#

moving to python's asyncio would strip out any eventlet / gevent support

#

as well as remove any support for most DB drivers (if you want to actually gain the benefit of being async)

wispy quail
#

well have you seen quart's support for the current ecosystem?

quick cargo
#

that's not the issue

#

quart is currently a optional thing you can do

#

which is fine for the people who want to use it

#

but if you're a large company that basically means completely re-writing the code base to keep with updates if flask merges into quart or vice versa

#

it would also mean you loose the incredible amount of db drivers like psycopg2, flasksqlachemy, datastax driver (scylla, cassandra etc..), mySQL etc...

#

i mean sure you can still use them

#

but then you completely loose the benefit of asyncio

analog gust
#

@quick cargo You seem to know about flask a bit. do you think you could help me with long polling with flask?

#

as in updating the webpage without have to refresh

grand oriole
#

is anyone willing to help me with these?

  1. how do i change my http this (http://IP:5000/) to https?
  2. how would i program something to receive https POST requests?
quick cargo
#

mmm its not something i would recommend really because it really hurts scaling and also eats up ports making it more vulnerable to attacks also things like tcp keep alive will prevent it working correctly alot of the time

#

then again any sort of constant connection opening like that unless you're using eventlet / gevent as flask's backbone is gonna be awkward but i would consider using a websocket because it's more widely supported and fixes keep alive issues

wispy quail
quick cargo
#

how do i change my http this (http://ip:5000/) to https?
You need to setup TLS/SSL with certificates etc... to become 'secure'

how would i program something to receive https POST requests?
Nothing changes framework side just server handling side which your webserver should do for you

quick cargo
analog gust
#

Thanks CF8 I will look into it

quick cargo
#

hence why i think moving to asyncio's async is a determent to the framework not a improvement

wispy quail
grand oriole
quick cargo
#

what program i need to run to do something when it receives a POST request
You dont run anything extra

grand oriole
quick cargo
wispy quail
wispy quail
wispy quail
grand oriole
#

is it not just in the code?

wispy quail
#

let cf8 speak

quick cargo
#

nothing you need to worry about code wise unless you're writing your own server

#

your webserver handles all that stuff

#

all you need is a cert and key file from a given provider and give it to the webserver to handle

#

gunicorn, hypercorn, uvicorn etc... all handle this for you

wispy quail
#

and force https if you want from the webserver

grand oriole
#

okay, thanks

#

what would i program to have my website do print() when a POST request is made?

wispy quail
#

Oh you really need to learn Flask, there is kind of much to be written

opaque rivet
#

what's the benefits of asgi over wsgi? wsgi can't handle 2 concurrent requests?

wispy quail
quick cargo
#

In reality it is, Quart compared to any other ASGI framework is pretty slow but in reality gevent and Flask already does a great job and provides performance enough for most people's need

wispy quail
#

That's it

quick cargo
#

the only advantage that really is useful with quart over flask is that you can:

a) use websockets in a sane way
b) use background tasks without a OS thread
c) make use of asyncpg

wispy quail
#

comparing side by side is not the perfect picture

quick cargo
#

in reality that's how everyone is gonna compare it because that's what matters

#

should we change our entire code base for a little more performance if we follow all these prerequisite? or should we just stay with our existing system that works well enough

wispy quail
quick cargo
#

yeah, but they're perfectly capable of just switching to gevent it's easy enought to do without modifying the existing code base much

wispy quail
#

don't blame me for some bad explanations in there though

quick cargo
#

i've seen that article already yes

#

im not saying it wouldnt be useful for some

#

but my original point that it's not useful enough to warrant upsetting the whole ecosystem

#

which is why im against the idea of flask going into the whole asyncio section when quart exists

#

but ig we'll just have to wait and see what happens

wispy quail
#

Well let me ask you: what is your framework of choice?

quick cargo
#

FastAPI probably

#

in the modern world of client sided apps and ajax like react, vue etc... FastAPI is basically the best tool you could ever have with python

wispy quail
#

The front-end world is decoupled and api-driven

quick cargo
#

yeah

#

why fastAPI is incredibly good for that

wispy quail
#

Why not other frameworks? Why Fast api?

wispy quail
quick cargo
#

auto doc page generation, validation, model creations, native support for pydantic, type conversion, great middlewares, performant

wispy quail
#

Tiangolo made sure to even provide a frontend demo

quick cargo
#

the fact it produces OpenAPI spec files that is built off the models you use is probably the biggest pull factor of the framework

wispy quail
quick cargo
#

because it means you can use any system that support OpenAPI and requires little to no effort on your behalf

wispy quail
#

i am currently writing those by hand

quick cargo
#
    @router.endpoint(
        "/{bot_id}/hide",
        endpoint_name="Hide Bot",
        description=(
            "Hides the bot from the public listing until it is re-approved.<br>"
            "*naturally this requires a super user key*"
        ),
        methods=["POST"],
        response_model=GeneralMessage,
        responses={
            401: {
                "model": GeneralMessage,
                "description": "The lacks the authorization "
                               "to perform this action.",
            },
            404: {
                "model": GeneralMessage,
                "description": "This bot does not exist in discodlist.gg",
            },
        },
        tags=["Bot Endpoints"]
    )
    async def hide_bot(self, req: Request, bot_id: int):
        ...

with a cheaky little custom framework wrapper ez pz

wispy quail
#

i guess this shows that being specific can give you edges. like a web framework can be a web framework but being api focused, it added stuffs to make writing apis enjoyable

quick cargo
#

its the whole do one thing and do it well principle

#

just hope i can get my webserver upto a stable enough state to use with my fastapi stuff πŸ˜…

wispy quail
#

one thing i cant find is a good mail sending and receiving soft for vms

#

if you have vm, you'd want mail sending. lets say you dont want the mailgun way

wispy quail
quick cargo
#

not something ive worked with

#

all that sort of stuff i leave to 3rd parties to deal with

visual fiber
#

could you please walk me through that code?

vestal dove
#

Could someone please tell me how to host a Flask app? I want to host it on a hosting service called Sweplox Hosting, it uses nginx for webhosting. I heard that it's possible with nginx.

astral dove
astral dove
# vestal dove I do have a VPS

I'd recommend this tutorial https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-20-04
It walks you through setting up Python on the server, installing and configuring a tool called uWSGI for the application server and Nginx for the webserver

DigitalOcean

In this guide, you will build a Python application using the Flask microframework on Ubuntu 20.04. The bulk of this article will be about how to set up the uWSGI application server and how to launch the application and configure Nginx to act as a fron

vestal dove
#

alright let me check

astral dove
#

If you don't have an Ubuntu server some of the commands will be slightly different, but it should get you on the right lines, especially around the config files

signal bronze
#

I'm new to flask, do i always have to put something in a <form> tag to get data?

torpid knoll
#

no, not necessarily but what do you mean by getting data

signal bronze
#

like a entry field, buttons

upper folio
#

I have build a small dynamic website with (mostly) Python. Till now I have only ran it locally (as all my projects till now). But iΒ΄d like to deploy it. The problem is that I have no experience in server security and am worried that my AWS instance I want to host the Website on will be hacked. What things do I need to consider to make my server secure, or can anyone of you point me to resources which might help me educate myself on the subject?

craggy axle
#

everyone seems like geniuses execpt for me

#

have you guys studied this

native tide
#

Hey, I'm running a page using aiohttp.web, but I was wondering if it's possible to run a task on the background that when a specific trigger is activated it opens a page

#

or maybe inside the html file using a JS script? rooThink

#

what I'm trying to do is, just when a page is opened, I have a barcode scanner and when I scan something I'm hoping to make it go to a page, like /scan/<barcode>/

haughty turtle
native tide
#

yes

#

and open a specific page when a barcode is scanned

#

but preferrably in background, so I dont need to press a "scan barcode" button

haughty turtle
#

But your scenario is a bit broad, so your barcode scanner is connectected to a computer?

#

You want it to open a web page on that computer that it's connected to only ?

native tide
#

yes

#

the page wont be opened on any other computer, its not publicly accessible

haughty turtle
#

Upong scanning have a background code that checks for barcodes scanned then have it open the browser /scan/<barcode>/

native tide
#

never used selenium before bonk

haughty turtle
#

Ah seems like you don't even need Selenium

haughty turtle
#

But this would require the user to have the web browser open, to read the data then on the web browser load. Again it depends on your needs if you need a background approach just scan and open a page, if not say your providing a bar scanning service web app then the second approach works.

native tide
native tide
#

I need a web developer to help me on a project

#

Dm me ^^

brisk spear
#

I will try it once I do flask properly

#

Is there any difference with flask and sanic ?

#

Can we make money with flask and other stuff ?

rapid bramble
#

Anyone who has experience with building PayPal based payments with Python & Flask?

wispy quail
wispy quail
#

An asgi framework. Btw sanic does not exist in Scrabble XD

wispy quail
brisk spear
#

Okay bro

weak anvil
#

How can I make render_template pass in variables as raw HTML in flask? It shows "s around the variables and renders them as text.

#

Solved:

from flask import Markup

@app.route("/")
async def return_some_html():
  return Markup("<p>Hi!</p>")
wind walrus
#

oh shoot so low quality

#

how can I add this feature

#

"Add new author"

#

so when the button is clicked, a new form entry appears

#

im using Flask

#

i assume this is javascript? but then how can i then receive it on the backend

weak anvil
#

doesn't work

wispy quail
#

just return it as a normal string

weak anvil
#

no it doesn't work inside rendertemplate

wispy quail
#

no return a raw string

weak anvil
#

it will return a quoted string

wispy quail
#

not inside render_template

#

like what i wrote above

weak anvil
#

yeah

#

but i need it inside render template

wispy quail
#

then use {{ somevar | safe }}

#

use the safe pipe

weak anvil
#

i solved it anyway, you can just do

return render_template("file.html", var=Markup("<p>text</p>"))
weak anvil
wispy quail
#

ok ^^

wind walrus
#

anybody know the answer to my question?

wind walrus
weak anvil
#

yeah you need javascript

#

make a flask route and then make a http request to it containing all the data you want to transfer, in json

#

@wind walrus

wind walrus
#

is this Ajax or JQuery stuff?

#

im not very familiar with js

weak anvil
#

doesn't matter, they do the same thing

wind walrus
#

oh okay

weak anvil
#

I'll dm you a js guide to follow, it's a good one

wind walrus
#

oh thx

lusty cloud
#

i'm getting a TemplateDoesNotExist at /categories/new
categories/category_form.html

#
TemplateDoesNotExist at /categories/new

raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: categories/category_form.html
green snow
#

is init file supposed to be empty?

lusty cloud
#

both are empty

inland copper
native tide
# lusty cloud
#dont forget to import os
'DIRS': [os.path.join(BASE_DIR, 'templates')],```
open tinsel
#

Anyone know anything about beautifulsoup ?

native tide
#

yep

open tinsel
#

where can I load the code?

native tide
#

wdym?

open tinsel
#

I have 75 lines I'm keen for someone to look at re bs

#

bit of a style overview

#

I have a couple of bs issues

#
# Calculate highcharts values from chart svg line coordinates and yaxis

from bs4 import BeautifulSoup
import locale

locale.setlocale(locale.LC_ALL, '')
gn = { "k" :' * 1e3', "M" : '* 1e6'}

def asnum(s):
    # Calculate number from short description
    return eval(''.join([gn.get(c, c) for c in s]), {}, {})

def get_yaxis_labels():
    # Should call with soup.find.string
    soupy = soup.find('g', {'class' : 'highcharts-yaxis-labels'})
    yaxis = []
    for i in list(soupy.children):
        yaxis.append([int(i.get('y')), i.text, None])
        yaxis[len(yaxis)-1][2] = (asnum(yaxis[len(yaxis)-1][1].strip('$, ')))
    return (yaxis)

def regression(yaxis):
    # Calculate slope from first and last points.
    # svg uses a top left coordinate system so intercept is chart top value.
    yaxis.sort(reverse = True)
    m = (yaxis[len(yaxis)-1][2]-yaxis[0][2])/(yaxis[len(yaxis)-1][0]-yaxis[0][0])
    b = yaxis[len(yaxis)-1][2]
    return (m,b)

def get_data_series(nseries):
    #  Should call with soup.find.String('g', {'class' : 'highcharts-series-'+str(series)})
    soupd = [[],[]]
    d_list = [[],[[],[]]]
    for series in range(nseries):
        soupd[series] = soup.find('g', {'class' : 'highcharts-series-'+str(series)})
        d_iter = iter(list(soupd[series].children)[0].get('d').split())
        d_list[series] = [[field, float(next(d_iter)), float(next(d_iter))] for field in d_iter]
    return (d_list)
#

def rnum(m, x, b):
    # Calculate number from regression
    return (m * x + b)

def ascur(s):
    return eval(''.join([gn.get(c, c) for c in s]), {}, {})

def main():
    pass

main()

# url = "https://www.investsmart.com.au/invest-with-us/investsmart-growth-portfolio"
filename = "urlPageSaved.html"
soup = BeautifulSoup(open(filename,'rb').read(), "lxml")

yaxis = get_yaxis_labels()
m,b = regression(yaxis)
d_list = get_data_series(2)

# Calculate yaxis values from chart svg line coordinates
# xaxis is one value at end of each month commencing Oct 2014
# each row
for r in range(len(d_list[0])):
    # each series
    for s in range(len(d_list)):
        d_list[s][r].append(rnum(m, d_list[s][r][2], b))
    print(locale.currency(d_list[0][r][3], grouping=True), locale.currency(d_list[1][r][3], grouping=True))

# print(*locale.currency(d_list[0][r][3], grouping=True), locale.currency(d_list[0][r][3], grouping=True), sep='\n')
#

I'm not sure why I can't use requests to grab the data. i had to download the page to a file

native tide
#

Maybe the website is not allowing you because you dont have a useragent

open tinsel
#

hmm, I don't really know much about js. Only really understood that the content doesn't exist until it is created in your browser which I understand it the issue.

native tide
#

something like this : ```from bs4 import BeautifulSoup
import requests
import lxml

def get_link_data(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
'Accept-Language': "en",
}

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
open tinsel
#

OK I'll look into that. What do I search for? BeautifulSoup agent ??

#

A fair amount of the site is secure scripts

native tide
#

User-Agent

#

or headers

open tinsel
#

but the download works to the cent.

#

in $15k

#

reconstructing with regression

#

Would I be able to pass soup.find('g', {'class' : 'highcharts-series-'+str(series)}) as an argument?

#

or something similar

#

The last double for loop is a bit of a train wreck too

#

The best way of using locale.currency has me a bit confused

#

!close

elder nest
#

is there a way to hide all of the codes and stuff from the url of a formhttps://fsdfdsfsdfsdsdfsdfs/dsdfsdfsdffsdsdf?code=&id=742942218687479828&prefix=.&welcome=795853980932505611&announcement=743525344900022363&logs=802882486090072104&join=808200474674069514&voice=%F0%9D%90%8C%F0%9D%90%9A%F0%9D%90%A2%F0%9D%90%A7&ticket=tickets&mute=743201784327045130&auto=743099370039410719&helper=743095944018526381&dj=743203167587532851

fierce thicket
#

Hello bro i have learned basics of django but i want to learn advance like how to insert data,deleting , edit and update ?

native tide
#

Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.

πŸ’»Code: https://github.com/codingforentrepreneurs/Try-Django

⭐️Course Contents ⭐️
⌨️ (0:00:00) 1 - Welcome
⌨️ (0:01:14) 2 - Installing to Get ...

β–Ά Play video
#

just go to the section your interested in

dull wigeon
#

how do i change what is displayed on the django admin page from email to a username

fallen meadow
#

hi jakey

dull wigeon
#

hi

opaque rivet
dull wigeon
#

thanks

opaque rivet
elder nest
sturdy coral
#

is there an API available which can give me access to audio files of all songs ?,trying to build a web music player

elder nest
#

like make it so its only domain/dashboard not domain/dashboard?sdfdsfsdfsdfsdfsdfsd

opaque rivet
elder nest
#

ok

#

how would I tell the browwser to only return the domain

#

and not the query params

opaque rivet
#

just keep splitting

native tide
#

just keep splitting

#

just keep splitting

elder nest
#

yes I understant I have to split the domain and the query params but if the browser used the codes how do I change it from with to without the codes

opaque rivet
#

what?

elder nest
#

like how do I show the user the domain without the code

opaque rivet
#

what code

elder nest
#

in their browser

#

https://fsdfdsfsdfsdsdfsdfs.com/dsdfsdfsdffsdsdf without the stuff after the ?

opaque rivet
#
split_url = url.split('?')
domain_and_path = split_url[0]
query_params = split_url[1]
mint folio
#

That’s your domain root so just point it there

native tide
#
split_url = url.split('?')
domain = split_url[0]
query_params = split_url[1]
elder nest
#

will that show the domain in the browser?

elder nest
opaque rivet
#

You need to understand what you are doing, here you are only splitting your URL at the ? character (splitting between your domain and the query params).

mint folio
#

I don’t understand. Why is that stuff their in the first place? What are you doing?

elder nest
#

like this

#

you see all of that stuff

#

I dont want it to be there but for the codes to still work

mint folio
#

Ok so are you submitting a form? Making a request? What is it your doing

elder nest
#

submitting a form

mint folio
#

So use POST request to submit the form

#

Then the parameters will be sent in the request body

opaque rivet
# elder nest like this

that data is there because you sent a GET request. Any data sent with a GET request are sent as query params...

mint folio
elder nest
#

will post still be able to be used in a python function in my app.py file

mint folio
#

Yeah

elder nest
#

ok

mint folio
#

It’s just submitting data

elder nest
#

how do I get data from the post?

#

@mint folio

mint folio
real hare
#

I got a function that parses data, and it returns a JSON string, but I wanna use that in my POST data but it sends the literal string as part of the query params, how do I construct a request in Flask to send it "properly"

#

?

#

the data shows like the following in the request.

"←[31m←[1mPOST /fetchmetadata/%5B%5B%22Return-Path%22%2C%20%22%3Cxxxxxx 

distant charm
#

hello so i was storing email and password from a form in session

#

and trying to access a page based on the session(trying to restrict direct acess)

#
    return super(SecureCookieSession, self).__getitem__(key)
KeyError: 'email'