#web-development

2 messages ยท Page 207 of 1

swift wren
#

i can post information through postman

inland oak
#

99% chance it is CORS then

native tide
#

How to change javascript quiz

inland oak
#

Postman is ignoring cors problems, unless you check some settings perhaps there

native tide
#

But nothing change

swift wren
#

cors is enabled

#

im pretty sure cors being enabled is the *

inland oak
#

show the logs in Network tab

#

for the axios request

swift wren
#

hang on how do i show the logs

native tide
#

idk javascript only copy and paste

swift wren
#

i can see the table and it shows that the request failed

inland oak
native tide
inland oak
#

I still remember what it showed it Network tab too

swift wren
inland oak
#

CORS.

#

I had exactly the same log

swift wren
inland oak
# swift wren

if you will change Axios request to GET type, you will find that it is working btw

#

that happened only in POST requests funnily

swift wren
#

i mean, thats fine and all

#

but why wont cors be enabled then

#

because obviously its attatched and initalised

#

and everytime the app is reloaded that loop runs for the with app.app_context()

#

also this obviously states to enable cors

#
@auth.route('/login', methods=['POST', 'GET'])
def login_route():
    print('hello world')
    username = request.json.get("username", None)
    password = request.json.get("password", None)
    print(f'username:{username} password:{password}')
    data = jsonify(request.json)
    data.headers.add('Access-Control-Allow-Origin', '*')
    return f"<h1>{request.get_json()}</h1>"
native tide
swift wren
inland oak
#

Funny. Google is not available

#

all other web sites are available

#

I can't google. what a nightmare

swift wren
#

i disabled the ssl and its telling me its a cors issue

#

aannnnddd its sending a request

native tide
swift wren
#

not entirely working

#

its telling me the request type is options

#

i remember having ot do that

inland oak
#

build flask app out of just 10 code lines as example with CORS allowed

#

and try it on it

inland oak
#

cors requires OPTIONS enabled in order to make preflight request

swift wren
#

i kinda did

#

i didnt have them specified and i recently specified

#

ill remove those constraints

#

wait

#

how come its telling me 404 when the flask server is picking up the requests

inland oak
#

ยฏ_(ใƒ„)_/ยฏ

swift wren
#

i hate js bro with the passion

#

if only browsers ran python

#

fucking lifes problems would have eased

swift wren
#

aint no fukcing wayu

#

im gonna die

#

my whole life's been a lie

dusk portal
drifting radish
#

why 91 line no working?

#

html

#

this

#

if form.validate_on_submit():

#

in sing-up

stable yew
#

i need some help in django

mystic wyvern
stable yew
#

right so heres the thing,
when you call a html page , the function is called, then what happends
is the html page generated then the proccess occurs. but for the proccess to occur there needs to be an interface(aka html page)

#

then why render html page at the end?

#

like here

#

lets say the proccess is storing details to a DB

#

when that happens why render after the operation over, am i misisng something?

#

@mystic wyvern

mystic wyvern
stable yew
#

yeah we need to render the page first

#

or is the function having GET and POST capabilities

#

and can i make seperate functions for generating the pages?

#

then carry out the functions

mystic wyvern
mystic wyvern
stable yew
#

but is it possible

#

like this

#

or something

mystic wyvern
stable yew
#

would you mind helping me out on vc if possible

mystic wyvern
stable yew
#

np

mystic wyvern
#

but last one thing

#

that why we use render in the bottom ,imagine that we put render at top what is gonna happen?

stable yew
#

return earlier

#

so essentially whats happening here is a get request is sent first to the function renders the page then details are entered, then post request is sent right?

serene prawn
stable yew
#

ok cool

stable bear
#

Hi. I am interested in learning about web development with django. Currently I am using the PyCharm Community edition IDE. For the front-end, I have read that HTML, CSS and Javascript will also be needed. However, PyCharm does not have support for CSS and Javascript, so is there any way to find a work-around for this problem?

drifting radish
#

Why submit no working

simple garden
#

how can i reduce in its height

#

and make the text align cause contact is a bit down for some reason

stable yew
#

its lighter and has alot of programming languages that it can support

stable bear
stable yew
#

You need to download python, pip install django

mystic wyvern
tawdry rose
#

'Response' object has no attribute 'get'
I am getting this error while trying to post data from front end to database using the User.object.create_user method in django kindly help me

unique epoch
#

is there a channel were i can ask about web scraping ?

#

specifically with selenium

next mulch
#

Hi I am using redis-py for a project
Can someone help me with it?

daring isle
#

Do you guys use viewsets or modelviewset?

vast rune
#

can anyone answer a question about django queue and threading?

thorn igloo
#

just ask your question mate

vast rune
#

well i have a consistent thread that is reading Serial data . Then i have consumer threads that open and need to access the data that serial thread queues. But since Django runs the functions from URL there is no easy way to pass the queue object between the threads

#

I use memcached.. I guess i could pass them that way. or use global queue

golden bone
mystic wyvern
warped aurora
#

How would I grab the one of the row values after clicking the edit button and use it to query the database?

serene prawn
daring isle
#

in your urls you have a path which passes in int:id, your edit button should href="" to the url, the url will be connected to a fnction in your views which handles the query

#
path('see_event/<int:id>', views.see_event, name='see-event'),
tawdry rose
# mystic wyvern can you post the whole code please

from django.contrib.auth.models import User
from django.shortcuts import render

Create your views here.

from werkzeug.utils import redirect

def signup(request):
if request.method == 'POST':
Username = request.POST['Username']
Firstname = request.POST['Firstname']
Lastname = request.POST['Lastname']
Email = request.POST['Email']
Password = request.POST['Password']
x = User.objects.create_user(username=Username, first_name=Firstname, last_name= Lastname, email= Email, password= Password)
x.save()
print('user created')
return redirect('/')
else:
return render(request, 'signup.html')

My code has multiple files since its a django based project above is the views.py files code

warped aurora
daring isle
#

then your views should pass in the id

#
def see_event(request, id):
   
    obj = Eventregister.objects.get(id=id)
    wcid = obj.wc_id

#

and you'd return a new template

#

if you want it in a modal....

#

you'll likely need js

#

actually

#

you can prob just pass the query in your view for the orginal page

mystic wyvern
daring isle
#

nah idk acc lol

tawdry rose
warped aurora
vast rune
#

look at network chrome degbug tab and make sure resp is coming in

#

correctly

mystic wyvern
tawdry rose
vast rune
#

make sure get is an option in views for that call

#

@api_view(['GET'])
def deviceSeq(request, pk):

tawdry rose
vast rune
tawdry rose
#

where shoul i add it ?

vast rune
#

you should always have something like this above the def or classes in your view @api_view(['GET', 'PUT', 'DELETE'])

daring isle
vast rune
#

im on react

#

much easier

mystic wyvern
#

@tawdry rose did it work ?

tawdry rose
#

i dont know what he is saying

mystic wyvern
#

just put this above your func @api_view(['GET'])

tawdry rose
#

ok ill try

vast rune
#

api is the name of MY app in django

#

i don't know your app name

#

prob the name of the folder your views.py is in

mystic wyvern
#

the api_view is a decorator that usually used in drf(Django Rest FrameWork )

warped aurora
tawdry rose
mystic wyvern
#

mmmm...

tawdry rose
#

then ?

mystic wyvern
#

last more thing

#

post your html file

#

the signup file

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.

vast rune
#

i have a consistent thread that is reading Serial data . Then i have consumer threads that open and need to access the data that serial thread queues. But since Django runs the functions from URL there is no easy way to pass the queue object between the threads
I use memcached.. I guess i could pass them that way. or use global queue

#

? (serial device streaming data to cpu via pyserial)

#
 stop_thread=False
q=queue.Queue(maxsize=100)
connectSerial()
t2= threading.Thread(target=consumer,args=(q),daemon=True).start()
time.sleep(5)
stop_thread=True

def connectSerial():
    ser = serial.Serial()
    ser.baudrate = 1000000
    ser.timeout=1
    ser.port = '/dev/ttyACM2'
    ser.open()
    t1 = threading.Thread(target = readSerial, args = (ser), daemon = True).start()
    
def readserial(ser):
    global stop_thread,q
    msg = bytearray()
    buf = bytearray() #trimmed at open must add back
    while True:  
        if(stop_thread):
            break
        try:
            while True:
                timelast=time.time()
                i = max(1, min(2048, ser.in_waiting))
                msg = ser.read(i)
                buf.extend(msg)
                a= msg[0:1][0]
                q.put(a)
                break
        except Exception as e:
            stop_thread=True
            ser.close()
            break
    stop_thread=True
    ser.close()


def consumer():
    global stop_thread,q
    while not stop_thread:
        if not q.empty():
            a=q.get()
            b=a*100
            print(b)
lavish prismBOT
#

Hey @tawdry rose!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

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

mystic wyvern
#

just post the form section

tawdry rose
# mystic wyvern last more thing

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Signup</title>
</head>
<body>
<form action="signup" method="POST">
{% csrf_token %}
Username:<input type="text" name="Username" ><br>
First_name: <input type="text" name="Firstname" ><br>
Last_name: <input type="text" name="Lastname" ><br>
Email: <input type="email" name="Email"><br>
Password: <input type="password" name="Password">
<input type="submit">
</form>
</body>
</html>

mystic wyvern
tawdry rose
#

i am getting the error only after runnung my website

mystic wyvern
tawdry rose
#

after submitting the signup

mystic wyvern
#

ok when you submitting the signup form in which view you redirect it ?

#

is it to the home view ?

tawdry rose
#

yes

mystic wyvern
#

ok when you signup and get the error did the user signup in the database ??

tawdry rose
#

yes

mystic wyvern
#

@tawdry rose show me your home view

tawdry rose
mystic wyvern
#

views

#

just the home func

tawdry rose
#

ok

#

from django.shortcuts import render
from django.http import HttpResponse

Create your views here.

def home(request):
return render(request, 'Home.html',{'title': 'Django' ,'link': 'http://127.0.0.1:8000/', 'link2':'http://www.youtube.com'})
def profile(request):
return render(request, 'Home.html',{'title': 'This is the Profile path'})
def Expression1(request):
a = int(request.POST['text1'])
b = int(request.POST['text2'])
c = a + 2*b
return render(request, 'Output.html',{'Output': c })

mystic wyvern
#

ahhh.

tawdry rose
#

?

mystic wyvern
#

i really got confused

#

last thing

#

your home.html

tawdry rose
#

ok

#

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Template1</title>
</head>
<body bgcolor="yellow">
<h1>Hello {{title}}</h1>
<a href={{link}}>Home</a>
<hr>
<a href={{link2}}>Youtube</a>
<hr>
<a href="app_signup/signup">Signup</a>
<hr>
<form action="Expression" method="POST">
{% csrf_token %}
1st Value:<input type="text" name="text1">
2nd Value:<input type="text" name="text2">
<input type="submit" >
</form>
</body>
</html>

late trail
#

I missed what's wrong with your code? @tawdry rose

mystic wyvern
mystic wyvern
mystic wyvern
late trail
#

if you allow it i think switch to react and use django for backend @tawdry rose

tawdry rose
native tide
#

hello, can anyone help me out in Beautiful Soup ?

lavish prismBOT
#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

distant trout
#

does anyone else think expo bundle size is too big?

daring isle
#

defined my css, i know its being imported correctly into the component -
how the hell do i change my navbar color?

#
return (
    <Box sx={{ pb: 7 }} ref={ref}>
      <CssBaseline  />
      <List>
        {messages.map(({ primary, secondary, person }, index) => (
          <ListItem button key={index + person}>
            <ListItemAvatar>
              <Avatar alt="Profile Picture" src={person} />
            </ListItemAvatar>
            <ListItemText primary={primary} secondary={secondary} />
          </ListItem>
        ))}
      </List>
      <Paper  
      
      sx={{ position: 'fixed', bottom: 0, left: 0, right: 0 }} elevation={3} >
        <BottomNavigation 
          className = 'bottom-nav' 
          showLabels
          value={value}
          onChange={(event, newValue) => {
            setValue(newValue);
          }}
        >
          <BottomNavigationAction label="Recents" icon={<RestoreIcon />} />
          <BottomNavigationAction label="Favorites" icon={<HomeIcon />} />
          <BottomNavigationAction label="Archive" icon={<ArchiveIcon />} />
        </BottomNavigation>
      </Paper>
    </Box>
  );
}
#

i set className = to my css element (there ws no classname here before)

#

I can put that anywhere else and it works except the place im trying to affect

willow shell
#

Basic terminology question:
Are there specific terms for endpoints which are intended for a client to access it vs endpoints which are only intended to be used as like an API?

#

I feel like I am misusing some of these terms a little bit

#

IE:
I have an API endpoint in Flask, lets call it /api/get_user_data, which just gets the saved data for the current user and returns it as a dictionary.

I would call this an API Endpoint ^

I also have an endpoint, lets call it /login which the client accesses to view the login page and log into the app.

Is there a term for this style of endpoint? ^

fading plinth
#

Can web development benefit from experience in solving dynamic programming problems?

vernal iron
#

Question for anyone using Vault or something similar: I have a Flask application and I want to store the DB creds in Vault and let the app fetch it with hvac client library. But how can the app safely auth to Vault? Storing the Vault token with the app would take me back to the original problem. The only thing I can think of is storing the token with the build process. I am planning on using GitLab CI for deployment and I know there is a feature for setting variables (which I believe makes them available as environmental variables during the pipeline process). Is this similar to how you folks handle fetching secrets for your apps? Are any security issues with this approach that I should be aware of?

haughty isle
vernal iron
# haughty isle Where are you deploying to? And what is Vault?

The ultimate goal is to deploy to a Kubernetes cluster but for right now, I am working locally with Docker containers (one for the Flask app, one for the database and one for the Vault server. Vault is a self-hosted product from Hashicorp that allows you to fetch secrets via API. The Flask app has a client library for fetching from Vault's API.

haughty isle
vernal iron
#

Directly on AWS EC2 instances

#

I know they have their own Kubernetes service, but this is a small side (i.e. their should be little load) project and given pricing, I'm trying it on just EC2 for now

haughty isle
#

Ah use AWS Secrets Manager

#

And configure an iam role on your ec2 machines that you want to access the secrets

vernal iron
#

eh, I'm looking specifically to get experience with Vault ๐Ÿคท๐Ÿพ

#

we have it at my job, so want to play around with it here. Also experience with situations where that kind tight integration between products is not available (i.e. how would I handle this if I want to move the app to some other cloud provider)

swift wren
#

i've used jwt's to start logged in sessions validated from flask backend with real data in the database
i just wanted to know how 2fa works right, like ik about sessionStorage()
but i feel like, if i develop a function that generates a random hexa code, how do i securely store it in the session so that the only person that see the real code is the email recipiant
im also doing the emailing system from the backend

stable yew
#

where am i going wrong here

golden bone
reef spruce
#

who know flask??

still root
#

Hey I need help with scraping a web page I don't know what it's not working.

#
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://www.ubereats.com/ca")
    print(page.title())
    page.fill("#location-typeahead-home-input", "address")
    page.keyboard.press("Enter")
    print(page.url)
    page.close()
#

Here is my python code.

#

This is the button I want to click or either press enter. It would do the same. However, whatever I try it always seems to be the same result and does not go past this page.

native tide
#

do I need anything else than Django, Node.js and Postgresql for a simple portfolio website?

thorn igloo
#

a simple portfolio is just a frontend application no?

native tide
#

well something like that I guess

thorn igloo
#

if there's like a contact me form, any backend works

#

doesn't have to be complicated

native tide
#

also would like to make simple website for uploading media

#

just for myself

#

aka buy VPS and just make my own cloud service

#

so I can sync stuff

thorn igloo
#

i see

native tide
#

I already did some simple website like that in only Django

#

I could upload files and then view it on the website

#

but idk I found it kinda hard to find a lot of good resources on Django

#

I get the basics of HTML, CSS, JavaScript, Postgresql and decent python

#

but idk stuff like website layout I was doing in Django and HTML but I see that you can do a lot more with JavaScript

thorn igloo
#

what do you mean you can do a lot more with javascript?

native tide
#

more animations visualizations and I think implementation is easier? also more documentation, sources

#

I think I m just going to look at some github projects with django

#

and see what and how people do stuff

thorn igloo
#

alright

golden bone
inland oak
lavish prismBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

inland oak
lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

timid tulip
#

Hello I'm trying to get started with Python to develop a web app, and would like to know what I need to know and to get started with it?

golden bone
#

!resources especially if you're starting from zero have a look ๐Ÿ‘€

lavish prismBOT
#
Resources

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

timid tulip
#

Thanks I will check that out.

native tide
#

also the class based stuff is harder to read than function based stuff

native tide
#

wow

#

30 minutes just to install react and other stuff, setup file structure and connect react, webpack, babel and some random shit xD

#

probably not gonna remember what any of those things are / do and how to use them

thorn igloo
native tide
#

well so I thought if I make it by myself I will understand better what is what

#

but yeah

#

honestly whats the advantage of js, react and all of that stuff

#

at the end of the day cant you make most stuff in just HTML and CSS and Django?

#

like from what I understand now is Iam using Django as backend simulating all stuff and html template

#

and then inside a html template I am inputting the react view I guess?

#
โŒจ NPM Setup Commands โŒจ 
npm init -y
npm i webpack webpack-cli --save-dev
npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev
npm i react react-dom --save-dev
npm install @material-ui/core
npm install @babel/plugin-proposal-class-properties
npm install react-router-dom
npm install @material-ui/icons
#

like this thing

#

then setting up file structures, different files, connecting them

#

idk feels like Im going to go through the whole tutorial

#

and gonna know some functionality but if something breaks or if I m gonna want to add new stuff I wont know where to add it and how to change stuff

dense slate
native tide
#

oh yes surely! but at the same time

#

if I import so many things

#

then knowing where to do what is hard

#

you can put functionality in both Im pretty sure

#

but I dont know where it should be done mainly

#

I read somewhere that views.py should be thin and models.py should have most code and be thicker

#

but its nothing I can be sure of ..

light ferry
#

@native tide i have a probleme bro ca you help me

native tide
#

yeah honestly its too much Im gonna drop it for now

dense slate
native tide
#

I have no idea what Im doing, I know how to write logic and similar, but with the react and all those different things, there is just too much to learn at once

dense slate
#

Yea, chip away. Best you can do.

native tide
#

I just want like simple website that I can upload stuff to

#

and then watch it

dense slate
#

All you need is Django.

native tide
#

I did it all in just django before

dense slate
#

And a DB - so postgresql is fine.

native tide
#

it just had really ugly styling and no structure

dense slate
#

I mean the DB is only if you're storing data.

native tide
#

yes I was using postgresql

dense slate
#

If you're making a simple CSS/HTML site with cool features and videos - you really only need a front end.

native tide
#

so what is react / node.js actually used for

#

is it just because there is already a lot of stuff there to use?

dense slate
#

It's the user-facing part of the site, built on mostly javascript.

#

Django can handle both front and back end, but React is a javascript-powered front-end framework that makes front-end dev easier and more productive.

native tide
#

but you can do most if not everything without javascript right?

dense slate
#

Most functionality yes, but if you want things like animations or changes to the site without refreshing, then you start needing the JS side of things.

#

Django will just give you CSS/HTML capabilities with templates.

#

You can do JS stuff within it for sure as well.

#

Definitely better to start with that then trying to learn React and Django at the same time.

#

At least that's my suggestion.

native tide
#

yes that seems more reasonable

#

to first build up the main site and then add maybe animated drop down menus or similar with js later on

native tide
#

And don't worry about setting things up yourself, just do create react app and get working

urban ridge
#

Hi all,

So I built webapp using django for a startup and I'm ready to deploy it. However, I'm struggling to find the right service to use! especially cost-wise.

General info:

  • Django 3.2, Python3.9, Postgres, couple dependencies

  • Few visitors to the webapp, barely 100s a month

  • Interactive with the database, it has some sort of a chat section, sign in and auth functionality, ...etc

First option I checked is AWS, and I think what's appropriate for this use case is "Amazon Lightsail" for $3 to $10, but when I add the database server the cost shoots up to $80+!

Same happened when I checked other services like Microsoft's azure!

I'm confused about the whole deployment process and it's frustrating to find A LOT of resource explaining code/frameworks and other technologies but almost NONE that explain how to make a use of it or actually deploy it and the cost behind it.

So I'm hoping this post receive deliberate responses and would be helpful for the experienced ones to share their knowledge. And if you happen to use these services or others, if you don't mind, share the prices and the use case.

I'm trying to find the most cost-effective approach for this case and future cases.

Thanks

golden bone
#

The big three are the most expensive. I would look at Heroku for starters. Even their free tier Postgres might be enough with such low traffic

dense slate
#

You can just increase your cost by small amounts as you scale and need more resources.

still root
still root
#

All I want to do is add a bunch of items to the shipping cart in Uber eats and get that URL so that I can send it to the user

inland oak
still root
#

Shopping cart*

inland oak
#

so in reality web scrapping is almost always illegal, except for when it is used in acceptance tests

inland oak
still root
#

Ya but I am not using web scraping data for my own use. I am using it to simply redirect the user to the same page

#

I just donโ€™t see why I need permission from Uber eats. I mean the person I am working for (he is a client of mine) most likely does

inland oak
still root
#

Ok let me read the Uber eats website rules and get back to u

#

Here is something I found

inland oak
#
Many people have false impressions about web scraping. It is because there are scrapers who donโ€™t respect intellectual property rights and use web scraping to steal content. Web scraping isnโ€™t illegal by itself, yet problems arise when people disregard websites' terms of service and scrape without the site ownerโ€™s permission. According to a report, 2% of online revenues can be lost due to the misuse of content through web scraping. Even though web scraping doesn't have a clear law and terms to address its application, itโ€™s encompassed with many legal regulations. For example: 
#
Donโ€™t copy data that is copyrighted.
 

One person can be prosecuted under several laws. For example, one scraped some confidential information and sold it to a third party disregarding the desist letter sent by the site owner. This person can be prosecuted under the law of Trespass to Chattel, Violation of the Digital Millennium Copyright Act (DMCA), Violation of the Computer Fraud and Abuse Act (CFAA)and Misappropriation.

It doesnโ€™t mean that you can't scrape social media channels like Twitter, Facebook, Instagram, and YouTube. They are friendly to scraping services that follow the provisions of the robots.txt file. For Facebook, you need to get its written permission before conducting the behavior of automated data collection. 
inland oak
# still root Here is something I found

here what you found.... but fullly

It is perfectly legal if you scrape data from websites for public consumption and use it for analysis. However, it is not legal if you scrape confidential information for profit. For example, scraping private contact information without permission, and sell them to a 3rd party for profit is illegal. Besides, repackaging scraped content as your own without citing the source is not ethical as well. You should follow the idea of no spamming, no plagiarism, or any fraudulent use of data is prohibited according to the law. 
#

basically care to read before giving partial information out of context

still root
#

Are you talking about yourself giving false information?

#

(No disrespect intended)

inland oak
#

just ask moderators to clarify that, I don't care about what you think beyond given information about it.

#

I do not have intention to spend time in pointless arguing

still root
#

It says even in what you sent me that as long as the data being sold isnโ€™t confidential it is legal. If I am making an app that literally redirects the user back to the same website I manipulated in order to get a unique URL. Tell me how that is illegal?

#

I am not trying to argue I just believe you werenโ€™t given enough context and didnโ€™t understand my post well enough to tell me if it is against the law.

inland oak
still root
#

A Google search is enough to tell you about this though. I also read the Uber eats rules and guidelines and I didnโ€™t find anything about them not allowing web scraping

inland oak
#
Restrictions.
You may not: (i) remove any copyright, trademark or other proprietary notices from any portion of the Services; (ii) reproduce, modify, prepare derivative works based upon, distribute, license, lease, sell, resell, transfer, publicly display, publicly perform, transmit, stream, broadcast or otherwise exploit the Services except as expressly permitted by Uber; (iii) decompile, reverse engineer or disassemble the Services except as may be permitted by applicable law; (iv) link to, mirror or frame any portion of the Services; (v) cause or launch any programs or scripts for the purpose of scraping, indexing, surveying, or otherwise data mining any portion of the Services or unduly burdening or hindering the operation and/or functionality of any aspect of the Services; or (vi) attempt to gain unauthorized access to or impair any aspect of the Services or its related systems or networks.
#
Ownership.
The Services and all rights therein are and shall remain Uberโ€™s property or the property of Uberโ€™s licensors. Neither these Terms nor your use of the Services convey or grant to you any rights: (i) in or related to the Services except for the limited license granted above; or (ii) to use or reference in any manner Uberโ€™s company names, logos, product and service names, trademarks or services marks or those of Uberโ€™s licensors.
#

This is literally link at your uber eats for terms of usage. This is your web site owners rules which you break. Find all the ones that you break if you wish there.

golden bone
#

I didn't see the original question and I don't want to debate what the law is, but unless your question is specifically about how to violate ToS there is probably a way for you to ask the question from a purely technical perspective (for example using a different website where it is definitely permitted)

inland oak
#

Perhaps <@&831776746206265384> could clarify to @still root that web scrapping services like that https://www.ubereats.com/ca against their consent and making third party software based on this data is not legal

still root
#

Ok I see what you mean. I didnโ€™t see that part. I just donโ€™t really understand why me manipulating the page so that I could get a unique URL from Uber eats and just send my user to it is illegal?

#

I am not scraping data from it, all of the actual data collection is done through an API which I know for fact is perfectly legal

inland oak
#

why did you use Selenium then

still root
#

Itโ€™s funny that u say that bc I didnโ€™t even use selenium

open forum
#

It's not illegal, but any kind of web automation is often violating the terms of service of the site.

#

It doesn't matter how you automate it, the terms are often phrased in terms of "don't use the site in any other way than manually through a browser"

inland oak
open forum
#

Your particular usage may not be harmful, but the rules imposed on us by Discord is to disallow any discussion or assistance of activities that violate the ToS of any other service.

#

So, if it's against the ToS, you can't talk about it here.

still root
#

Well I am just trying to determine if I should actually make this for my client or should I probably let them know that it is illegal? I just want to be educated. But I understand what you are saying

#

Thanks a lot, I appreciate it

inland oak
open forum
#

Violating terms of service is not illegal, it just means the site is saying "If you do this, we will block access to our service".

inland oak
#

Some countries could be having it literally illegal

still root
#

I still want to respect Uber eats terms though

#

But thanks for the information

open forum
inland oak
open forum
still root
#

Ok well thanks for the help, I truly appreciate it

open forum
#

I have worked on a project that did do this, but it was a very special case, because my employer was a significant operator in a market where our service indirectly benefitted the services we were automating, and those services were aware of what we were doing and implicitly approved of it even though what we did technically violated their stated terms.

#

That's a very special situation, though.

still root
#

This project is generating Uber eats leads, so in a way it is kind of benefiting them?

near ridge
#

It's different in this case. It violates our rules to assist with things like this

#

Regardless of whether or not it benefits them

#

It violates their ToS, which means we won't assist

still root
#

Ok ok let's stop talking about this in that case. As if right now I am most likely not going through with this.

near ridge
#

Fair. I mean you raise reasonable questions, I'm not dismissing that.

#

More just making sure we're on the same page regarding that project and us as a server

#

Same rules would apply to Dem if he came to us about his work project

#

Special case or no, we personally can't verify and so we take a blanket stance

still root
#

Yes, of course. I understand.

golden bone
#

I won't drag this channel any further off topic but if this servers' policy is that using tools like Selenium without explicit permission is somehow inherently a violation of rule 5, that should be specified because it's not obvious or logical

native tide
paper moon
#

So I have my backend implemented in flask, and I have made my frontend in HTML. How can I make it so that when a button is clicked in the frontend, some information is shown on the website? Basically how to make the frontend communicate with the backend?

golden bone
paper moon
golden bone
paper moon
#

Thanks!

lavish prismBOT
#

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

dark night
#

In a flask project, where should I keep my database models? I started using Blueprints, so I have moved my routes into different directories and now I can't use my post request routes without referencing the models somehow. I've been getting circular import errors while trying to figure it out

golden bone
warped aurora
#

trying to prepopulate a wtform field from a database object like this

    vehicle = Vehicle.query.filter_by(T_Number=T_Number).first()
    form = vehicle_form()
    form.T_Number = vehicle.T_Number
    form.white_plate = vehicle.white_plate

    return render_template("update.html",
                           T_Number=T_Number,
                           form=form
                           )

<form action="" method ="post" class="modal-form" id="edit-form">

    <h3>Edit Vehicle details</h3>
    {{ form.T_Number(class_="edit-input",placeholder="")}}
    {{ form.white_plate(class_="edit-input",placeholder="")}}
    {{ form.submit(class="btn btn-primary btn-md btn-block w-100 mb-2 shadow")}}
  </form> ```

getting this error
{{ form.T_Number(class_="edit-input",placeholder="")}}
TypeError: 'str' object is not callable
native tide
#

would this code be vulnerable to SQL injection? ```php
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/core/config.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/core/session.php");

$token = $_GET['t'];

$TokenSQL = 'SELECT * FROM users WHERE auth = "'.$token.'";';
$prep = $conn->prepare($TokenSQL);
$prep->execute();

$results = $prep->get_result();

$final = mysqli_fetch_assoc($results);

if ($final > 0) {
echo 'true';
} else {
echo 'false';
}
?>```

#

i am use prepared statements

tropic raptor
#

how to compare both timezone-aware time() objects?

#

It isn't possible without date, right? -> due to iimpossibility of localizing time without date, hm?

dark night
# golden bone models.py in the same folder with all your routes usually http://exploreflask.co...

Thanks for the sources, I had the right idea but I think my issue now is that my db variable from SQLAlchemy requires my app variable, and creates a loop of imports between my modules. I found an example of a project avoiding the issue by using db=SQLAlchemy() without the app variable, but then I run into the issue of not being able to use the model again. Do you happen to know a solution?

golden bone
#

Just a screenshot of your project structure and import statements might help

simple garden
#

what does :not do?

native tide
#

in python?

#

unless it's a newish feature that is not python

#

it might be

simple garden
#

in web dev

native tide
#

not up to date with python

simple garden
#

im asking in web development cause its in css

#

theres like :hover and there :not

native tide
#

ok, not python, css

simple garden
#

and i dont know what it does

#

yes

#

css

native tide
#

not sure

#

give me a minute

simple garden
#

yes i saw it but i didnt understand it

#

thats why im asking here ;-;

native tide
#
#

it's a negation

#

run the example above

dense slate
#
Our CSS would select all the <li> elements except the one(s) with a class of .different.

/* Style everything but the .different class */
li:not(.different) {
  font-size: 3em;
}
simple garden
#

ohhhh

#

got it

native tide
#

noice

simple garden
#

does it apply for words?

native tide
#

no

#

there's no css selector for words/strings

simple garden
#

got it

#

unless i use span

dense slate
#

Even with #?

simple garden
#

right?

native tide
#

am with # you select id= I think?

#

sorry, I'm far behind my css

dense slate
#

Right, oh I was understanding the question incorrectly I think.

austere relic
#

same as with any other computer

unkempt temple
#

How similar is ruby on rails to python with django?

daring isle
#

am i heading in the right direction? currently no idea how to get this shown in react

#

but ive done the model and serialising right so far right?

#

this shit is so much more confusing than jinja templating

stable yew
#

print(Details.objects.filter(Username=user,Password=passw))

#

what dos this command do in django

daring isle
#

i dont think it will do much, it will likely give you an object identifier

#

make this a variable:

#

objects = Details.objects.filter(Username=user,Password=passw).all()

#

then:

      print(object)
#

or something like that, you'll get a readout

#

prob better if you define what you want to see if its not working like , print(object.id) or any field you want

#

this part 'Details.objects.filter(Username=user,Password=passw).all()' is filtering everything in your Details model and returning anything with the password = passw

inland oak
#

it automatically transforms to SQL query(like the one above) and accesses your Sqlite or Postgresql (or Mysql) database
returns result and automatically converts to python objects

stable yew
#

But I didnt

#

(case if password correct)

inland oak
inland oak
#

debug

#

check what u have in database

#

Details.objects.all() will get all existing details objects in db

inland oak
#

it is not a boolean operation

stable yew
#

How do I make it so that it checks if the local variable password matches with the username actuall password in the db

inland oak
#
Details.objects.filter(Username=user,Password=passw).first() is not None
#

that would be a boolean result

stable yew
#

What is .first

inland oak
#

remember, you get the list

stable yew
inland oak
#

ID is only part of the instance

stable yew
#

Yeah

pallid lily
#

how to i reference a one to one field from parent ```py
class Profile(models.Model):
id= 1
name = 'Potato'

class Settings(models.Model):
id = 1
profile = models.OneToOneField(Profile)

#

is it reference like profile.settings?

stable yew
#

.first() gives the first value from the db ?

#

Is that what you mean tbyfirst object instance

inland oak
stable yew
#

Oh

inland oak
#

instance of class object

stable yew
#

Oh ok

pallid lily
#

can some one look at my question please :d

stable yew
#

As a bool variable

#

Also can I use Auth0 ? Or django inbuilt auth

#

?

daring isle
inland oak
#

it should do nothing additional in behaviour

daring isle
#

then its not about how it looks just that its not needed

#

i thought you meant the whole sentance

inland oak
daring isle
#

bad habit ๐Ÿ˜†

stable yew
inland oak
# daring isle bad habit ๐Ÿ˜†

I had it too. except I did it like objects = Details.objects.all().filter(Username=user,Password=passw) Select all and then filter out of them ;b

stable yew
#

Can someone reply

inland oak
#

those are separated concerns and responsibilities and completely not related to each other

#

well technically related since auth can use your Django ORM as a source of users for verification

#

but that depends on the chosen auth

daring isle
#

i have an avatar in one of my components overlapping my sidebar.
how do i define the hierarchy ?

#

the avatar is on a card which stays behind the navbar like it supposed to

#

*in React

stable yew
stable yew
#

what does this simply return

#

Details.objects.filter(Username=user,Password=passw)

#

like only this withought the first()

#

also here when i inter the right password

#

it redirects me to the registration page whihc means the password was wrong ut it really wasnt

#

@inland oak

daring isle
stable yew
#

im getting None returned

inland oak
inland oak
stable yew
#

this is returning none to me

inland oak
stable yew
#

welp

#

lol

stable yew
inland oak
stable yew
#

and if i use Details.objects.filter(Username=user,Password=passw).first() returns joe no matter what

#

theres some thing wrong with the validation

#

either both are wrong sets of validating, or im blind

stable yew
#

cool

daring isle
#

are your field names capitalised in your database?

#

what are you trying to achieve? a login page ?

daring isle
#

i have my route set up and working api side, in react when i click a user in the user list to get to a page with their details - its refreshing the page and returning to index and giving this error.
Can anybody help?
im using a Link href in the component, its showing as the correct address in the bottom left with the pk:id after the /

native tide
#

Helloo, what do you guys recommend to use for user authentication? Is it (custom) sessions or tokens, or the two combined?

It's for login management

wise kite
#

after deployment gunicorn is not able to read gunicorn.sock becouse of enforcing mode. but if i change it to permissive it work

native tide
daring isle
#

i just used the login_manager when i used flask

#

loginmanager*

rotund perch
#

Hello, I use built it Django features and I often try to avoid overriding because I see it a complicated part for me. Is it possible to tell what things are usually overridden (and what things we have not to touch) and in what classes/functions. For example, we can override the **save** method inside the **model** class to edit the way of saving the models in the database, we can override the **serializer** so we can add additonal fields, etc. I know thats so general but I hope someone gives me a refrence atleast for the most often overridden things in Django.

daring isle
#

hey bro

#

i dont know about a list but if you search ovveride in the documentation it gives you quite a lot of results

eternal blade
native tide
#

Hello everyone

#

I am developing a python app flask which is called by an another app via URL : https://host name:port/arg1=mdp &arg2=user -->hostname is my iis web server where i deployed the app. I would like to have a log per user --> when the user run the app it should normally create his own log and write in it, but unfortunately the mainthread write in all the logs of all users . I have tried : lock thread, multilogging, semaphore, socketio, calling with start-newthread -->No success ๐Ÿ˜ฆ Thanks for help

#

anyone can help please?

daring isle
stable yew
eternal blade
#

But it doesn't lemon_thinking

eternal blade
daring isle
native tide
#

actually, when running the app it creates a log wit username and should looging in it

stable yew
#

can anybody hel me with this, been trynna solve this issue for hours, its not authenticating the password and username properly from Db, i think there might some problem with the db or im using the wrong way of auth.

daring isle
#

you're definitely not using the way i auth

native tide
stable yew
#

i have tried using authenticate tooo

stable yew
daring isle
#

JWT

stable yew
#

ahh yes ik about that

#

but

daring isle
#

are you making an api or normal django?

stable yew
#

im trying to authenticate the basic way first

stable yew
daring isle
#

let me check my django app files one sec

stable yew
#

oke

#

lmk if oyu wanna check my code

daring isle
#
@incorrect_user
def login_user(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        try:
            user = authenticate(request, username=username, password=password)
        
            login(request, user)
            
            return redirect('home')
        except:
            messages.info(request,' username/password are incorrect')
            return redirect('login')
       

    else:
        
            
          

        return render(request, 'authenticate/login.html', {})
stable yew
#

thats exactly what i tried using

#

it returns None

daring isle
#

try this...

stable yew
#

i typed in the corrct pass and username

daring isle
#

replace your variables with strings

#

in your filter

#

and see if it works

stable yew
#

alright

daring isle
#

if it does then you know its an issue with your data fetch

stable yew
#

nope still doesnt work

#

returns None

#

can you show your models?

warped aurora
#

how do you access field data when looping over a wtform?

          <div class="form-group">
            <label for="title">{{field.label.text}}</label>
            <input type="text" name="title" placeholder=""
                   class="form-control"
                   value="{{field}}">
          </div>
        {% endfor %}```
getting none
stable yew
warped aurora
#

form.fieldname returns the value but I'd rather not have to type that out for every fieldname

native tide
daring isle
#

my models are the standard django users

stable yew
daring isle
#

Instead of creating a custom user model i just used foreign key to link to the fields i needed in a seperate table

daring isle
#

did you change your auth user model

stable yew
#

like username,password in one table and details in another?

#

if you think technically authenticate(Username=inp,Password=inp2) should return NOT NONE if the details are right

#

but it doesnt

native tide
#

i wanna learn coding

#

it seems interesting

daring isle
#

did you change your auth user model?

#

in settings

#

AUTH_USER_MODEL ='appname.ModelName'

stable yew
#

lemme check

daring isle
#

change this for your app and paste it in the bottom

#

AUTH_USER_MODEL ='members.NewUser'

native tide
#

why doesnt this work? ```php
<?php
$JobID = $_GET['jobid'];

$output = shell_exec("D:\xampp\htdocs\HumaniumPY\CloseJob.py {$JobID}");
print ($output);
?>``` my python script works fine but it is my php i think

stable yew
#

only one i have is AUTH_PASSWORD_VALIDATORS

daring isle
#

Yeah you wonโ€™t have

#

You need to create it

#

Paste it in

#

I think it defaults to the django user model otherwise

#

Make sure you change it to your appname then a โ€œ.โ€ Then your model name

stable yew
#

ok

daring isle
stable yew
#

is it caps sensitive

#

the model/app name

daring isle
#

yes

stable yew
#

Details in my model name

daring isle
#

show me your details model

daring isle
stable yew
#

yeah

#

?

daring isle
#

you need this in it

USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['sername', 'Password']
stable yew
#

oh

daring isle
stable yew
#

im sorry im new to django ๐Ÿ˜ฆ

#

ignore the other class

daring isle
#

under your region paste the code i put

stable yew
#

ok

daring isle
#

then try authenticate again

#

this might not work, because you might need to abstract it first, but im seeing if it works directly- i dont really know.

if it doesnt you can do it the other way

stable yew
#

big yikes

#

oh zamn

#

you know what

daring isle
#
@property
    def is_staff(self):
        return self.is_admin

    @property
    def is_anonymous(self):
        return False

    @property
    def is_authenticated(self):
        return True

    class Meta():
        db_table = 'auth_user'
        verbose_name = 'User'
        verbose_name_plural = 'Users'
stable yew
#

ill try rebuilding my model

#

ill come back

daring isle
#

you need these under your def

stable yew
#

class meta?

#

ohh

#

ok

daring isle
#

infact

#

best thing

stable yew
#

yes ๐Ÿ˜ฆ

#

tell me

stable yew
#

:pog:

#

pog

#

ill do it

#

thanks

#

ill get back

warped aurora
# daring isle what are you trying to achieve

Basically I'm trying to edit a row in the database, so I'm prepopulating the form fields so the user can edit and then submit. But there are a lot of fields so instead of typing out

                   class="form-control"
                   value="{{form.field}}">
``` for every form field, I wanted to just loop over the fields
daring isle
#

what result you getting right now?

warped aurora
#

so first I was trying to do this

   value ="{{field}}"```
that returns None...then i tried value ="{{field.data}}" which was also none...so I then i checked form.data and then returned a dictionary with the {"field_header":None.....} for all fields
#

so form.data is empty

daring isle
#

try take it out of the divs

#

and render straight to the page

#
{% for f in form %}
{{f.label}} <br>
{{f}}
{% endif %}
#

put a br nex to that second {{f}} too

#

then see if your form getting rendered , it wont be pretty

#

but at least then you know its your div syntax and not you form

warped aurora
#

So it's showing empty inputs for all the fields

daring isle
#

did you state the intial data in your view?

warped aurora
#

but the labels are outputting correctly

#
    vehicle = Vehicle.query.filter_by(T_Number=T_Number).first()
    form = vehicle_form()
    form.T_Number = vehicle.T_Number
    form.year = vehicle.year```
daring isle
#

so in your case replace my obj in my instance with vehicle

#

it should populate your form with the first entry like in your query

#

it should look like that

#

wait

#

lol

warped aurora
#

lol?

daring isle
#
form = vehicle_form(instance=vehicle)
#

try that

warped aurora
#

so just passing the whole query result to the form

daring isle
#

yeah

#

because the form is linked by the model in the forms.py

#

so it knows what to do with the goods

warped aurora
#

the forms got a submit field at the end, and the model has relationship at the end, is that problem?

daring isle
#

you mean submit button?

warped aurora
#

yea

#

submit = SubmitField("Submit")

daring isle
#

just make sure your syntax is like this:

<form method='POST'>
(% if statement and form stuff % }
{% end for%}
<button stuff>
</form>
#

i had my button value="save" and it worked out well for me, not sure if its necessary

#

and in view i had

            vehicle= form.save(commit=False)
            form.save
            vehicle.save() 
#

make sure you're passing your vehicle object through your context to the template too

warped aurora
#
    __tablename__ = "vehicle"
    T_Number = db.Column(db.String(10), primary_key=True, index=True, nullable=False)
    white_plate = db.Column(db.String(10))
    green_plate = db.Column(db.String(10))
    status = db.relationship('Status', backref='details', lazy=True)

class vehicle_form(FlaskForm):
    T_Number = StringField(validators=[Length(1, 14)])
    white_plate = StringField(validators=[Length(1, 64)])
    green_plate = StringField(validators=[Length(1, 64)])
    submit = SubmitField("Submit")

@app.route("/update/<T_Number>", methods=("GET", "POST"), strict_slashes=False)
def update_details(T_Number):
    vehicle = Vehicle.query.filter_by(T_Number=T_Number).first()
    form = vehicle_form(instance=vehicle)
    return render_template("update.html",
                           T_Number=T_Number,
                           form=form
                           )

<form action="" method ="POST" class="edit-form" id="edit-form">
      {% for field in form %}
        {{field.label}}
        {{field}}
      {% endfor %}
  </form> ```
warped aurora
daring isle
#

oh snap you're on flask

warped aurora
#

Loool

daring isle
#

i thought you were on django lol

warped aurora
#

oops

daring isle
#

acc

#

maybe not even necessary

#

is it working so far?

warped aurora
daring isle
#

ok you need

#

vehicle= "query here"

    form = VehicleForm(obj=vehicle)
    if form.validate_on_submit():
        form.populate_obj(vehicle)
        db.session.commit()

warped aurora
#

Ah!

#

changing it to obj=vehicle did something

daring isle
#

did it do the right thing ?

warped aurora
#
      {% for field in form %}
        {{field.label}}
        {{field.data}}
      {% endfor %}
  </form>``` so this is now returning the corresponding values
daring isle
#

ok nice one!

warped aurora
#

thanks! now to get it looking good

#

the loop is also including the crsf token as an input field lol

daring isle
#

lol, just move it above the loop but under the <for> tag

#

<form>

daring isle
eternal blade
#

Its case sensitive, but I use the same capitalization in all places so it shouldn't be a issue

daring isle
#

the two users in that sentance are different capitalizations

warped aurora
# daring isle <form>

the submit field has also been included as an input, so I'm going to have to exclude the last 2 elements in the loops i guess

#

{% for field in form if field.widget.input_type != 'hidden' %} takes care of the CSRF

daring isle
#

your token shouldnt be inside your for loop tags it should be out of them

#

same with your button

#

token above them and button below them

#

change your form action as well, the one i posted is for my project

warped aurora
daring isle
native tide
#

Is there someone who is familiar with PHP and Python?

#

I have this code in PHP and I need to write it in Python

eternal blade
#

The User in the channel name is also uppercase py self.channel_name = f"User-{user.id}"

eternal blade
#

the User in the channel name is also capital so it shouldn't be a problem

#

But when I do py async_to_sync(channel_layer.send)( f"non-existant-channel", { "type": "non-existant", "payload": MessageSerializer(instance).data, }, )

#

It should error but it doesn't ๐Ÿค”

daring isle
#

so its either not reaching your if statement, or its not registering that its created

eternal blade
#
if created:
        chat_group = instance.channel.chat_group
        for member in chat_group.members:
            print("dispatching message to user", member.user.name)
            async_to_sync(channel_layer.send)(
                f"User-{member.user.id}",
                {
                    "type": "chat_message_create",
                    "payload": MessageSerializer(instance).data,
                },
            )
            print("sent message to user", member.user.name)```
#

both of the print statements get printed

daring isle
native tide
#

how do i block people from viewing my .py scripts on my apache webserver?

#

i am not good with config stuff

#

any way to convert Pillow image to django image field without having to save the image

daring isle
#

saw this online under the consumer class:

async def receive(self, text_data):
        # give control back to the loop, `chat_message` is triggerd
        await self.channel_layer.send(self.channel_name, {
            "type": "chat.message",
            "text": "1",
        })
eternal blade
native tide
#

I should use Tensorflow in backend. It takes a lot to load it...I just need to use method "predict" for model- is there any way to load just that method to speed up request?

eternal blade
inland oak
native tide
inland oak
native tide
#

in Tensorflow it's used like this "model.predict(...)"

inland oak
native tide
#

Do you mean how my imports look like?

inland oak
native tide
#

import tensorflow as tf
model = tf.keras.models.load_model('handwritten_character_classifier_model.h5')

#

@inland oak

inland oak
#

here you go, you don't need to import tensorflow any longer ๐Ÿ˜‰

#

if will not help you though, because I have a feeling that 99% of your time is taken by model loading

native tide
#

and I also need to use these lines:

#

model.predict(img_array)

#

keras.preprocessing.image.load_img(img_path, target_size=(160, 160))

inland oak
#

you just need to make that model would be loaded just once

native tide
#

keras.preprocessing.image.img_to_array(img) * (1.0 / 255)

#

tf.image.rgb_to_grayscale(array)

inland oak
#

minimize amount of times when you load the model

native tide
#

keras.preprocessing.image.array_to_img(array)

#
from gan import EnhanceAgent
from basicsr.archs.rrdbnet_arch import RRDBNet
import flask
from PIL import Image
import io
import numpy
import cv2
import StringIO


upscale=EnhanceAgent(
    scale=4,
    model_path="ImageEnhance.pth",
    model=RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4),
    tile=0,
)

@app.route("/enhance", methods=["POST"])
def enhance():
    if flask.request.method =="POST":
        if flask.request.files.get("image"):
            image=Image.open(io.BytesIO(flask.request.files("image").read()))
            image=np.array(image)
            final=upscale.enhance(image, outscale=3.5)
            return final

#

I have the following flask view and I want to test it using the command line, how would I do so?

#

is there any way to test it without making an interface for it

inland oak
#

use flask test client to request its end points with comfort in pytest

native tide
#

@inland oak Are you familiar with Flask?

inland oak
native tide
#

but this is fine too

native tide
#

yeah can I use cURL?

#

how would I do so?

#

there's no url to test

inland oak
#

curl can make POST requests

native tide
#

ok so then how would I do so, there's no url?

#

if you're running the dev server, something like curl 127.0.0.1:5000/enhance and you'll have to specify your payload

#

could also write a small client with requests in python

#

when I run python flask run, it doesn't start the dev server

inland oak
# native tide ok so then how would I do so, there's no url?

better to do that by the link I provided. because it allows to have it as unit test which requires nothing to launch except pytest command

otherwise people also make testing in staging environment.
That happens where they deploy to special environment for testing
and then run curl or pytest tests or anything else

unit tests are faster and easier than integration tests in general

native tide
#

I don't want to extensively test, I just want to make sure the flask wrapper is returning something reasonable

inland oak
#

flask run / gunicorn / or whatever you use in order to deploy it

#

it does not matter

native tide
tight ocean
#

Does anyone have experience with myplotlib in python?
There's one thing I don't seem to get it work
It'd be lifesaving if anyone could help me

#

Ping me if you are interested to help

native tide
#
from gan import EnhanceAgent
from basicsr.archs.rrdbnet_arch import RRDBNet
import flask
from PIL import Image
import io
import numpy
import cv2
import StringIO


app=

@app.route("/enhance", methods=["POST"])
def enhance():
    
    if flask.request.method =="POST":
        if flask.request.files.get("image"):
            image=Image.open(io.BytesIO(flask.request.files("image").read()))
            image=np.array(image)
            upscale=EnhanceAgent(
    scale=4,
    model_path="ImageEnhance.pth",
    model=RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4),
    tile=0,
)
            final=upscale.enhance(image, outscale=3.5)
            return final


#

whenever I run the following commands set FLASK_APP=enhance.py

#

and flask run

#

I get the following error:

#
Error: While importing 'enhance', an ImportError was raised.
austere relic
#

also, this is the wrong channel

tight ocean
#

I have been stuck forever lol

paper moon
#

So I have a function named test on the backend, how can I call it in the jinja template? Should I pass it to the context and just simply do test() in the html file with the required args?

paper moon
#

Flask

tight ocean
paper moon
#

But I am using jinja as the templating engine, so ig the procedure should be the same for all modules, no?

tight ocean
#

But I currently have this

daring isle
tight ocean
#

Each section has its own color, but I also want it to have text each section

daring isle
#

Yeah just put it in your route

paper moon
#
@app.route("/")
def home():
    return render_template("home.html.jinja", test)

Something like this should work?

thorn igloo
#

yea I'm not that advanced of a matplotlib user

paper moon
#

Well context is a dict cz it is **context, so I am guessing there is something missing here

daring isle
#
def home():
      test()
    return render_template("home.html.jinja")
paper moon
#

wait no

#

I want to get input from a textbox and pass it to the function

#

!d flask.render_template

lavish prismBOT
#

flask.render_template(template_name_or_list, **context)```
Renders a template from the template folder with the given context.
paper moon
#

see, there's a context arg too

daring isle
#

you define it in its own thing before you call it

paper moon
daring isle
#

and when you call it you put the value you need as the arg

paper moon
#

ah cool

daring isle
#

you can put the output into contect not the function

#

context*

paper moon
#

Huh?

tight ocean
#

Can anyone else help me?

paper moon
#

wym output?

daring isle
paper moon
#

well it varies, since it depends on the arg passed to it, and I get the arg from the textbox in the HTML file

daring isle
#

so after a form submit?

paper moon
#

yea

#

Its like, the person clicks the button, the textbox's value is passed to the function and the result is shown on the website

daring isle
#

you can grab the form data in the same function i think

#

its like 1 line of code

#

but depends on your requirements

paper moon
#

I am confused rn ngl

daring isle
#

lol, why dont you try explain exactly what you're trying. i may have already done it

#

whats the end goal

paper moon
#

The user inputs a string in the textbox, clicks the submit button, jinja gets the input and passes it to a function (not this one, but the main function also returns a dict of the same type) and then the dict is shown on the website with a for loop

daring isle
#

ok so excuse my terminology im quite new...

#

jinja aint doing shit except displaying your stuff. what will happen is the original function you have the form in will receive the form data

paper moon
#

Mhm

daring isle
#

once you have it captured there, you're then moving to another template right?

paper moon
#

No

#

The page is the same

#

istg I should just use dash/pywebio or something

daring isle
#

somebody else will have to chime in if thats possible, because i think these forms are post , so will reload your page

paper moon
#

oh

daring isle
#

i guess you could do an if statement

paper moon
#

hmm i'll figure it out thanks

daring isle
#

like if submitted in request true

paper moon
#

BTW have u ever used dash or streamlit or smth?

daring isle
#

you know the easy/lazy answer to this is store the input it in your database lol, then it will be there for sure regardless

tight ocean
#

Does no one have experience with matplotlib?

paper moon
daring isle
inland oak
#

It is more related channel for this

tight ocean
#

Will do

daring isle
#

trying to drill down from a list of users to a single user view.
working fine in postman but im getting this error and my app is refreshing.
any ideas anyone?

#

I have a link on a card for each user and Iโ€™m passing a href /userlist/ + {item.id}

dense slate
#

Want to show the js code?

#

That's what's causing your error.

daring isle
# dense slate Want to show the js code?
import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';
import { Route, BrowserRouter as Router, Switch } from 'react-router-dom';
import App from './App';
import Header from './components/Header';
import Navbar from './components/Navbar'
import Footer from './components/Footer';
import Register from "./components/register";
import Login from "./components/login";
import Logout from "./components/logout";
import BottomNavBar from "./components/FixedBottomNavigation";
import Userlist from './Userlist';
import Single from './components/Single';
import SingleUser from './SingleUser';

const routing = (
    
    <Router>
        <React.StrictMode>
            {/* <Header /> */}
            <Navbar />
            <BottomNavBar />
            <Switch>
                
                <Route exact path="/" component={App} />
                <Route path="/register" component={Register} />
                <Route path="/login" component={Login} />
                <Route path="/logout" component={Logout} />
                <Route path="/userlist/" component={Userlist} />
                <Route exact path="/userlist/:id/" component={Single} />
            </Switch>
            
            
            
        </React.StrictMode>
    </Router>
);

ReactDOM.render(routing, document.getElementById('root'));

#

this is my index.js

#
<Route exact path="/userlist/:id/" component={Single} />

this is where im trying to go

#

forget the "exact" part i just added

#

this is where im trying to go...

#

not letting me post ...
but im sure the destination isnt the problem its my routing

#

Iโ€™m new to react and tried following a tutorial and applying my own use case ,

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.

inland oak
#

use js tag

daring isle
#

if you see the bottom left the address seems fine when i hover over

#

Not sure how to use js tags

#

I've created the viewset and serializer, i just cant figure out how to get to a specific record

dense slate
#

Usually that's an issue with how you're calling or setting state.

#

So I have the feeling it's in one of your components.

daring isle
#

i think you're right

dense slate
#

What is Userlist? Is it undefined?

#

You might need to set Userlist before you apply it to your route - thus needing a useEffect.

daring isle
#

its the component im trying to call the url from

dense slate
#

Print it to your console.

daring isle
#

import React, { useEffect, useState, useRef } from 'react';
import './App.css';
import Posts from './components/Posts';
import Users from './components/Users';
import PostLoadingComponent from './components/PostLoading'
import Stylesheet from './components/Stylesheet';
import Mylogo from './components/Mylogo'


function Userlist() {
  const PostLoading = PostLoadingComponent(Users);
  
  
  const [appState, setAppState] = useState({
    loading: false,
    userlist: null,

  });
  useEffect(() => {
    setAppState({ loading: true });
    const apiUrl = 'http://127.0.0.1:8000/api/userlist/';
    fetch(apiUrl)
      .then((data) => data.json())
      .then((userlist) => {
        setAppState({ loading:false, userlist: userlist });

      });
    
      
      

  }, [setAppState]);

  


  
  return (
    <div className="App">
      
      
      <h1>User List</h1>
      <PostLoading isLoading={appState.loading} userlist={appState.userlist} />
      
     
    </div>

  );
}
export default Userlist;
dense slate
#

If it's a function, then it needs to be Userlist() i would think

daring isle
dense slate
#

Otherwise you're just trying to use a Userlist function, not what it returns.

daring isle
#

now i have a blank screen with the correct url listed

dense slate
#

Neato

daring isle
#

aha progress, thaks man

dense slate
#

Yep yep

daring isle
#

oh no, this makes the whole app blank lol

#

i gotta go watch spiderman, guess i'll try later!

native tide
#

do I need to restart my computer after pip installing opencv to make it work?

#

I just pip installed it however when I try to import cv2, it throws a modulenotfounderror

regal carbon
#

how do you build a post archiving website/webapp?

#

which tech stack to use

#

how to even start?

thorn igloo
#

list your requirements for this webapp. from this requirements you'll be able to determine what you need and choose the stack that will meet your needs

regal carbon
#

It can scan documents and can be used offline

#

and store those documents in a database but i dunno which one

native tide
#

Does anyone have experience with hosting Flask app on Heroku?

#

How should this line look in Heroku?

#

serve(app, host="0.0.0.0", port=8080)

thorn igloo
#

wait*

thorn igloo
regal carbon
#

ya

thorn igloo
#

i mean there's PWAs, but im sure there's like limitations to what you can do with that

thorn igloo
#

im not sure what your serve function is doing, but basically you need a Procfile file

thorn igloo
#
web: gunicorn wsgi:app
native tide
thorn igloo
#

here wsgi refers to the filename where i've important app if that makes sense

regal carbon
#

is PWA like .NET?

thorn igloo
#

progressive web app

#

google

thorn igloo
#

you have serve(app, host...) etc, what is serve here?

#

you're the one using it

#

i'm just mentioning it

thorn igloo
#
from app.main import app

if __name__ == "__main__":
  app.run()
#

this is the contents of my wsgi.py file

#

obviously you can name this anything, just make sure your Procfile reflects that

thorn igloo
regal carbon
#

no

thorn igloo
#

so why are you worrying about a tech stack when you haven't fully listed your requirements for the app

thorn igloo
#

so here's some more info on the procfile

river pelican
#

Anyone here who's a superboss with Dash?

tight ocean
#

Does anyone have experience with matplotlib and would like to help? :)

native tide
#

Do someone know how should I change it for Heroku?

thorn igloo
#

all you need for heroku is a Procfile as i've mentioned

native tide
#

Thanks, I will google about Procfile

thorn igloo
native tide
thorn igloo
#

wait, you don't know what the requirements.txt thing is

#

this is just a list of your installed python dependencies

native tide
#

I see, that was my assumption

#

But what's gunicorn?

river pelican
native tide
#

Another dependecy?

thorn igloo
#

basically a webserver thing

#

it's what heroku will use to run your web app

native tide
#

@thorn igloo How do I know what should I put in requirements.txt? Basically what I import and gunicorn?

wise osprey
#

has someone made an inventory management like app in Python?

thorn igloo
#

assuming you're using a virtual environment

#

if you're using the global installation, it will list every package you've ever installed and you dont really want that

native tide
thorn igloo
#

no, it will create the requirements.txt file based on the python libraries you have installed

native tide
thorn igloo
#

...

#

better to just use a virtual environment in the first place

native tide
#

@thorn igloo Can you pls explain virtual environment in context of using Heroku?