#web-development
2 messages ยท Page 207 of 1
99% chance it is CORS then
How to change javascript quiz
Postman is ignoring cors problems, unless you check some settings perhaps there
hang on how do i show the logs
idk javascript only copy and paste
i can see the table and it shows that the request failed
a week ago I was sure I had enabled them too.
but it was still CORS problem ๐
How to change quiz plz help
help
I still remember what it showed it Network tab too
if you will change Axios request to GET type, you will find that it is working btw
that happened only in POST requests funnily
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>"
bro for christ sakes learn some js would ya
Funny. Google is not available
all other web sites are available
I can't google. what a nightmare
i disabled the ssl and its telling me its a cors issue
aannnnddd its sending a request
how to change questions
not entirely working
its telling me the request type is options
i remember having ot do that
https://flask-cors.readthedocs.io/en/latest/
try some minimalistic example out of examples in docs
build flask app out of just 10 code lines as example with CORS allowed
and try it on it
you did not enable somewhere whiltelist that allows only GET POST?
cors requires OPTIONS enabled in order to make preflight request
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
ยฏ_(ใ)_/ยฏ
i hate js bro with the passion
if only browsers ran python
fucking lifes problems would have eased
Brython

why 91 line no working?
html
this
if form.validate_on_submit():
in sing-up
i need some help in django
what is the the problem ?
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
you mean why we didn't put render in the top of the func ?
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
for this point yes the func can have get or post or maybe put(update)
i dont think you need this
i didn't understand 100% but i think no
would you mind helping me out on vc if possible
mmmm.. actually i can't right sorry
np
but last one thing
that why we use render in the bottom ,imagine that we put render at top what is gonna happen?
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?
@stable yew You should really look into forms
https://docs.djangoproject.com/en/4.0/topics/forms/
ok cool
is this correct?
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?
Why submit no working
how can i reduce in its height
and make the text align cause contact is a bit down for some reason
just use VSCODE
its lighter and has alot of programming languages that it can support
do i need to install an extension?
You need to download python, pip install django
i believe you can write box-sizing: border-box to reduce the height
'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
Hi I am using redis-py for a project
Can someone help me with it?
Do you guys use viewsets or modelviewset?
can anyone answer a question about django queue and threading?
just ask your question mate
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
This one is probably as good as any
can you post the whole code please
How would I grab the one of the row values after clicking the edit button and use it to query the database?
Probably have button leading to another page that allows to edit specific entry given it's id ๐
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'),
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
actually wanted to do it in a popup modal
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
In which line did the error occurs ?
nah idk acc lol
after running my website and filling the form i am getting the error response object has no attribute get
Ok I'll try it this way first,
if you can let me see the error
see on the left screen
make sure get is an option in views for that call
@api_view(['GET'])
def deviceSeq(request, pk):
are you talking to me?
yep
where shoul i add it ?
in view.py. the view that is called must have that method
you should always have something like this above the def or classes in your view @api_view(['GET', 'PUT', 'DELETE'])
this is one of the reasons im moving to react, i dont like this method of doing things.
@tawdry rose did it work ?
i dont know what he is saying
just put this above your func @api_view(['GET'])
ok ill try
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
the api_view is a decorator that usually used in drf(Django Rest FrameWork )
Yea been thinking I should start learning that as well
it is showing this error now
then ?
!code
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.
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)
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.
just post the form section
<!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>
Oh! I didn't see any error
i am getting the error only after runnung my website
after running or after submit the signup?
after submitting the signup
ok when you submitting the signup form in which view you redirect it ?
is it to the home view ?
ok when you signup and get the error did the user signup in the database ??
yes
ok then the problem is in the home view
@tawdry rose show me your home view
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 })
ahhh.
?
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>
I missed what's wrong with your code? @tawdry rose
wait a minute what is werkzeug.utils??????
.
the redirect should import like that ```from django.shortcuts import render,redirect
if you allow it i think switch to react and use django for backend @tawdry rose
Thanks a lot its working now..
I want to become your coding buddy
hello, can anyone help me out in Beautiful Soup ?
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:
does anyone else think expo bundle size is too big?
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
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? ^
Can web development benefit from experience in solving dynamic programming problems?
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?
it didnt work ;-;
Yes
/login is just a regular endpoint. https://12ft.io/proxy?q=https://stevenpcurtis.medium.com/endpoint-vs-api-ee96a91e88ca
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.
Where are you hosting the kubenetes cluster?
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
Ah use AWS Secrets Manager
And configure an iam role on your ec2 machines that you want to access the secrets
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)
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
where am i going wrong here
It's telling you that login.html doesn't exist, so does it? And if so is it in the correct location?
who know flask??
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.
I am expecting this page to go past https://www.ubereats.com/ca but for some reason it returns the same exact address
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.
see
appname/appname/template
do I need anything else than Django, Node.js and Postgresql for a simple portfolio website?
a simple portfolio is just a frontend application no?
well something like that I guess
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
i see
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
what do you mean you can do a lot more with javascript?
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
alright
I don't know playwright but have done this in Selenium and I would usually tell it to wait for the URL to change. It's possible that it's printing and closing too fast before the new page loads
<@&831776746206265384> !rule 5
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
!rule 5 <@&831776746206265384>
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
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?
You'll want to know the basics of HTML and Python if you don't already. Then I would recommend following a tutorial or two for Flask, as this is a simple but popular Python web framework. Maybe find something specific to the type of web app you want to build
!resources especially if you're starting from zero have a look ๐
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thanks I will check that out.
Just use some react and node
thats what Im going with right now but there is a lot of setting up honestly
also the class based stuff is harder to read than function based stuff
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
why not just use create-react-app?
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
If there's one thing I've learned, it is that good development skills includes when to find ways to reduce creating things from scratch by using libraries and such. Some people much better than us have created validated ways of setting things up - CRA and CNA are examples of that.
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
but its nothing I can be sure of ..
@native tide i have a probleme bro ca you help me
yeah honestly its too much Im gonna drop it for now
Yea that's right, but models.py is more for inherent things to a model. Like if you want to return the review count for an item, you could create a method versus a generic view. Views are more for page functionality while methods for object/model based functionality.
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
Yea, chip away. Best you can do.
All you need is Django.
I did it all in just django before
And a DB - so postgresql is fine.
it just had really ugly styling and no structure
I mean the DB is only if you're storing data.
yes I was using postgresql
If you're making a simple CSS/HTML site with cool features and videos - you really only need a front end.
so what is react / node.js actually used for
is it just because there is already a lot of stuff there to use?
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.
but you can do most if not everything without javascript right?
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.
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
I mean yes but you'll get more powerful ui functionality from react
And don't worry about setting things up yourself, just do create react app and get working
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
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
I love Digital Ocean. $6/month, maybe $10/month if necessary for the extra RAM for FE frameworks, will cover that need.
You can just increase your cost by small amounts as you scale and need more resources.
Web scraping is perfectly legal though?
5$/month DO ;b
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
it is legal, but illegal to scrap against consent of owners ;b
Shopping cart*
so in reality web scrapping is almost always illegal, except for when it is used in acceptance tests
have you gained permission of Ubereats for that?
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
because you are using not your own property against consent of the owners (it is often forbidden in web site rules)
Ok let me read the Uber eats website rules and get back to u
Here is something I found
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.
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
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
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.
There is quite funny acronym IANAL = I am not a lawyer. As well as you are. None of us are comptent enough to know if we break the law in this doubtful situation
You should clarify if you are breaking law with lawyer or at least with web site owners.
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
https://www.uber.com/legal/en/document/?name=general-terms-of-use&country=great-britain&lang=en-gb have you read this fully?
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.
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)
Here is the origins
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
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
why did you use Selenium then
Itโs funny that u say that bc I didnโt even use selenium
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"
Because yes you break their terms of services, and secondly your actions can lead to harming their proffits because of whatever you are doing there against their property and explicit disagreement. That's usually it. Your automating software can just take money out of them by increasing load to servers which were not intended to be used like that
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.
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
Again, it's not illegal.
Write to help support of the web site and clarify if you have permission or not
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".
That can be different in different countries technically.
Some countries could be having it literally illegal
I am not a lawyer in any country, obviously, but I've never heard of that being the case.
as well as I am not a lawyer. But that's gray area for sure at least and where better be careful and to find all the possible information if dealing with it.
Whether it's a good idea to violate terms in a commercial project depends on the project and the market. As a rule of thumb, it's probably not usually a good idea, though.
Ok well thanks for the help, I truly appreciate it
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.
This project is generating Uber eats leads, so in a way it is kind of benefiting them?
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
Ok ok let's stop talking about this in that case. As if right now I am most likely not going through with this.
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
Yes, of course. I understand.
Logging in to a service isn't a violation of ToS AFAIK
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
Y'all should check out this app fissmic if you want to turn a website into a windows app. https://fissmic.github.io
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?
Your button can reload the page, or load a different one. Look at Jinja templates if you haven't yet. Anything more sophisticated will require htmx or JavaScript
it should get some data from the db and show it on the page. I have a function for that on the backend
So yeah that's basic Flask stuff. Your button can load a page based on a Jinja template and insert the data value
@paper moon like this https://stackoverflow.com/questions/28029448/how-to-pass-data-from-database-to-html-using-jinja2-flask-and-mongodb-and-while
I am confused about passing data from database (mongodb) to html.
I have python code in "init.py" that queries database using while logic - see below code snippet:
from pymongo import MongoClient...
Thanks!
:x: According to my records, this user already has a mute infraction. See infraction #57293.
Ruh roh.
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
models.py in the same folder with all your routes usually http://exploreflask.com/en/latest/organizing.html
Or if you need to have multiple modules, a models.py in each https://www.digitalocean.com/community/tutorials/how-to-structure-large-flask-applications.amp
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
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
how to compare both timezone-aware time() objects?
It isn't possible without date, right? -> due to iimpossibility of localizing time without date, hm?
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?
Sounds a little beyond me but I'd be curious to see the code. Maybe grab a help channel and see if someone more advanced can chime in
Just a screenshot of your project structure and import statements might help
what does :not do?
in web dev
not up to date with python
ok, not python, css
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;
}
noice
does it apply for words?
Even with #?
right?
Right, oh I was understanding the question incorrectly I think.
same as with any other computer
How similar is ruby on rails to python with django?
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
print(Details.objects.filter(Username=user,Password=passw))
what dos this command do in django
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
This command makes SQL query to your database
it is equvalent to
SELECT details FROM Details_table
WHERE Username=user, Password=passw
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
So in that case, then I was supposed to get a true value and return Render a page
But I didnt
(case if password correct)
This looks silly. It is equvalient to filter and then for some reason to request all objects again. all() will do nothing.
But I didn't
debug
check what u have in database
Details.objects.all() will get all existing details objects in db
The query resulrns List of DetailsObjects
it is not a boolean operation
How do I make it so that it checks if the local variable password matches with the username actuall password in the db
Details.objects.filter(Username=user,Password=passw).first() is not None
that would be a boolean result
What is .first
getting first object from the list
remember, you get the list
Like the first Id value in the db
first object instance.
ID is only part of the instance
Yeah
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?
Let's say we have 10 values in the db
.first() gives the first value from the db ?
Is that what you mean tbyfirst object instance
Details.objects.first()
will return return first object of Details, yes.
Oh
returned object is
Class:
pk # ID
your attributes # and etc
instance of class object
Oh ok
can some one look at my question please :d
And like you said I could use a variable also right
As a bool variable
Also can I use Auth0 ? Or django inbuilt auth
?
what looks silly? adding .all()
yes
it should do nothing additional in behaviour
then its not about how it looks just that its not needed
i thought you meant the whole sentance
.all() part should be not needed in objects = Details.objects.filter(Username=user,Password=passw).all()
that what I mean to say
bad habit ๐
@inland oak
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
Can someone reply
u can use whatever sort of auth u wish on top of using ORM
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
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
ahh ok
CSS attribute
z-index: 0;
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
legend
im getting None returned
An object similar to List, which is named smth similar to QueryList or smth like that
Make better test coverage with pytest
this is returning none to me
Don't ping me to question, ask everyone
when i use tis it returns mama no matter what even uif password is correct
write tests, seek errors earlier
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
cool
are your field names capitalised in your database?
what are you trying to achieve? a login page ?
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 /
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
after deployment gunicorn is not able to read gunicorn.sock becouse of enforcing mode. but if i change it to permissive it work
help
what platform?
I'm using flask
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.
hey bro
Django, API, REST, Home
i dont know about a list but if you search ovveride in the documentation it gives you quite a lot of results
Hey, https://stackoverflow.com/questions/70375371/channel-layer-send-not-calling-event-handler
Please check my question, Thanks
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?
wow Thank you!
sorry bro beyonf my level, but what action is supposed to call the consumer function in this setup?
yes i was trying to create a login page, yes my fields in db are capatilized
The async_to_sync(channel_layer.send)() should call the chat_message_create method of ChatConsumer
But it doesn't 
Any debug print statements in chat_message_create don't get printed
you need an if funtion to check if a log exists , and if not create, then write
actually, when running the app it creates a log wit username and should looging in it
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.
you're definitely not using the way i auth
it initialise it in the root function upload
i have tried using authenticate tooo
which method do yu use
JWT
are you making an api or normal django?
im trying to authenticate the basic way first
normal django registration login website
let me check my django app files one sec
@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', {})
try this...
i typed in the corrct pass and username
alright
if it does then you know its an issue with your data fetch
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

form.fieldname returns the value but I'd rather not have to type that out for every fieldname
i open the log with 'a' mode
does your database return anything when you print all? beside the auth
my models are the standard django users
using Details.objects.all() it prints all the Usernames
Instead of creating a custom user model i just used foreign key to link to the fields i needed in a seperate table
can you give me an example
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
i needed my users to be assinged to a 'branch' , so i set up a table called profile which has the username as a foreign key of the** user table** and **branch ** as a foerign key of a table of branches
did you change your auth user model?
in settings
AUTH_USER_MODEL ='appname.ModelName'
change this for your app and paste it in the bottom
AUTH_USER_MODEL ='members.NewUser'
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
i dont even have that variable available
only one i have is AUTH_PASSWORD_VALIDATORS
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
ok
interesting and stressful if you're like me
yes
what are you trying to achieve
show me your details model
pls
you need this in it
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['sername', 'Password']
oh
show me your model for details
under your region paste the code i put
ok
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
@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'
you need these under your def
follow this
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
what result you getting right now?
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
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
So it's showing empty inputs for all the fields
did you state the intial data in your view?
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```
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
lol?
so just passing the whole query result to the form
yeah
because the form is linked by the model in the forms.py
so it knows what to do with the goods
the forms got a submit field at the end, and the model has relationship at the end, is that problem?
you mean submit button?
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
__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> ```
do you mean pass the vehicle object in render_template?
oh snap you're on flask
Loool
i thought you were on django lol
oops
nah
ok you need
vehicle= "query here"
form = VehicleForm(obj=vehicle)
if form.validate_on_submit():
form.populate_obj(vehicle)
db.session.commit()
did it do the right thing ?
{% for field in form %}
{{field.label}}
{{field.data}}
{% endfor %}
</form>``` so this is now returning the corresponding values
ok nice one!
thanks! now to get it looking good
the loop is also including the crsf token as an input field lol
does it matter that this user is capitalised?
f"User-{member.user.id}",
Its case sensitive, but I use the same capitalization in all places so it shouldn't be a issue
the two users in that sentance are different capitalizations
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
try:
<fieldset>
{{ form.csrt_token }}
{% loops %}
<Divs>
{ % endloop %}
<button>
</fieldset>
</form>
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
Ye but the problem is that they are form attributes so looping through the form will always return them i think, even if I manually place the token and button outside.
Ah ok I forgot that quirk Iโm flask
Is there someone who is familiar with PHP and Python?
I have this code in PHP and I need to write it in Python
Can you show me where?
The User in the channel name is also uppercase py self.channel_name = f"User-{user.id}"
f"User
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 ๐ค
so its either not reaching your if statement, or its not registering that its created
Any print's in the if statement gets printed though
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
do you need a receive? or no?
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
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",
})
I don't think its compulsory
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?
It didn't work with and without the receive method
no idea how Tensorflow is structurized, but that can be possibly of help
from PackageName import DesiredMethod
Do you know how can I locate package name for predict?
I am having no idea what you are talking about
You said from PackageName...I am not sure to what package function predict belongs
in Tensorflow it's used like this "model.predict(...)"
provide example of code how you reach the model.predict()
Sorry, I am not sure what you mean by "how you reach the model.predict()"
Do you mean how my imports look like?
provide sufficient enough example of code that covers how it goes from importing library to using predict
import tensorflow as tf
model = tf.keras.models.load_model('handwritten_character_classifier_model.h5')
@inland oak
you can replace to
from tensorflow.keras.models import load_model
model = load_model('handwritten_character_classifier_model.h5')
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
and I also need to use these lines:
model.predict(img_array)
keras.preprocessing.image.load_img(img_path, target_size=(160, 160))
you just need to make that model would be loaded just once
keras.preprocessing.image.img_to_array(img) * (1.0 / 255)
tf.image.rgb_to_grayscale(array)
minimize amount of times when you load the model
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
https://flask.palletsprojects.com/en/2.0.x/testing/
have you tried reading this?
use flask test client to request its end points with comfort in pytest
@inland oak Are you familiar with Flask?
I used it a year ago.
I said goodbye to it back then ;b
well i was hoping that I could just make a cURL to test it
but this is fine too
Do you mean, write a test, or make sure the endpoint returns something manually? If a manual test, curl, httpie, postman shoudl work
yeah can I use cURL?
how would I do so?
there's no url to test
pytest is cooler than curl.
nothing stops you from using curl though
curl can make POST requests
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
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
I don't want to extensively test, I just want to make sure the flask wrapper is returning something reasonable
run it as server in whatever you can
flask run / gunicorn / or whatever you use in order to deploy it
it does not matter
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
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
this file is named enhance.py
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.
just ask
also, this is the wrong channel
I'm trying the text property in matplotlib to work, but it won't unfortunately
I have been stuck forever lol
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?
what are you trying to do
Django ?
Flask
I want percentage texts like this
But I am using jinja as the templating engine, so ig the procedure should be the same for all modules, no?
But I currently have this
In django , in the view / url method of doing things .
Your view is fired off when you visit a url you route so itโs easy .
You just put your stuff between the function name and return lol
Each section has its own color, but I also want it to have text each section
Let me check for flask
Yeah just put it in your route
The test function, for now is
def test(name):
return {"name": name}
@app.route("/")
def home():
return render_template("home.html.jinja", test)
Something like this should work?
yea I'm not that advanced of a matplotlib user
Yeah
Wait
No
Well context is a dict cz it is **context, so I am guessing there is something missing here
def home():
test()
return render_template("home.html.jinja")
wait no
I want to get input from a textbox and pass it to the function
!d flask.render_template
flask.render_template(template_name_or_list, **context)```
Renders a template from the template folder with the given context.
see, there's a context arg too
yeah got you, you just put the arg in the function ()
you define it in its own thing before you call it
and when you call it you put the value you need as the arg
ah cool
Huh?
Can anyone else help me?
wym output?
the output of your function
well it varies, since it depends on the arg passed to it, and I get the arg from the textbox in the HTML file
so after a form submit?
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
you can grab the form data in the same function i think
its like 1 line of code
but depends on your requirements
I am confused rn ngl
lol, why dont you try explain exactly what you're trying. i may have already done it
whats the end goal
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
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
Mhm
once you have it captured there, you're then moving to another template right?
somebody else will have to chime in if thats possible, because i think these forms are post , so will reload your page
oh
i guess you could do an if statement
hmm i'll figure it out thanks
like if submitted in request true
BTW have u ever used dash or streamlit or smth?
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
nope
Does no one have experience with matplotlib?
never used it sorry. try #โ๏ฝhow-to-get-help
you're going to need javascript if you dont want a page reload
Ask in #data-science-and-ml
It is more related channel for this
Will do
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}
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 ,
!code
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.
use js tag
if you see the bottom left the address seems fine when i hover over
the full api address in django is
http://localhost:8000/api/userlist/1/
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
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.
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at Userlist
i think you're right
What is Userlist? Is it undefined?
You might need to set Userlist before you apply it to your route - thus needing a useEffect.
its the component im trying to call the url from
Print it to your console.
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;
If it's a function, then it needs to be Userlist() i would think
that did something,
Otherwise you're just trying to use a Userlist function, not what it returns.
now i have a blank screen with the correct url listed
Neato
aha progress, thaks man
Yep yep
oh no, this makes the whole app blank lol
i gotta go watch spiderman, guess i'll try later!
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
how do you build a post archiving website/webapp?
which tech stack to use
how to even start?
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
It can scan documents and can be used offline
and store those documents in a database but i dunno which one
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)
you want a web app that's capable of working offline
ya
i mean there's PWAs, but im sure there's like limitations to what you can do with that
like, for heroku
im not sure what your serve function is doing, but basically you need a Procfile file
oh boi,
and inside that have something like
web: gunicorn wsgi:app
What you mean by serve function? What's Procfile?
here wsgi refers to the filename where i've important app if that makes sense
is PWA like .NET?
it's the file you need to run your web app on heroku
you have serve(app, host...) etc, what is serve here?
you're the one using it
i'm just mentioning it
like for example
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
back to this, do you have a structure of how you want to store your stuff?
no
so why are you worrying about a tech stack when you haven't fully listed your requirements for the app
so here's some more info on the procfile
Anyone here who's a superboss with Dash?
Does anyone have experience with matplotlib and would like to help? :)
In local environment I have this code
Do someone know how should I change it for Heroku?
all you need for heroku is a Procfile as i've mentioned
Thanks, I will google about Procfile
yes, you will also need to add gunicorn in your requirements.txt
Damn, new terms - gunicorn and requirements.txt
wait, you don't know what the requirements.txt thing is
this is just a list of your installed python dependencies
I have my issue specified in the #help-carrot channel
Another dependecy?
@thorn igloo How do I know what should I put in requirements.txt? Basically what I import and gunicorn?
has someone made an inventory management like app in Python?
pip freeze > requirements.txt
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
What will pip freeze do? Look into my files and see what I import?
no, it will create the requirements.txt file based on the python libraries you have installed
Nice, so I will just delete libraries that I don't use
@thorn igloo Can you pls explain virtual environment in context of using Heroku?