#web-development
2 messages · Page 217 of 1
Replit?
Anyone has experience building small real-time web apps and has suggestions for libraries to use when async operations are needed + with a mix of API's ? Am I good to go with FastAPI + python-socketio + asyncio ?
Got a Selenium project I'm working on but after a while the webpage decides to hang and needs the driver resetting. What's the best way of handling it, just a try except catching a TimeoutException and calling a method from there to reset the driver?
hey y'all if someone of you knows a little bit about APIs, could maybe have a quick look at #help-grapes ?
I do not understand why my code enters the if statement even though the response code is 200?
does selenium give you a responsecode? because if so, that was my approach and i still have a problem with it in #help-grapes
Have a issues with celery+flask
I have celery work fine on its own but when I add it to a flask app. it does not parse the url correctly and tries to connect to localhost.
The only way I was able to get it working was to call Connection directly.
from flask import Flask
from celery import Celery, shared_task
import ssl
app = Flask(__name__)
url = 'amqps://user:pass@host:5671'
app.config.update(
CELERY_BROKER_URL=url,
CELERY_RESULT_BACKEND='rpc://',
BROKER_USE_SSL={'cert_reqs': ssl.CERT_NONE},
CELERY_TIMEZONE='UTC',
CELERY_DEFAULT_QUEUE='TEST'
)
def make_celery(app):
celery = Celery(
app.import_name,
backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(app)
@shared_task(task_ignore_result=True)
def addCall(a, b):
return
def my_ext_caller(a, b):
from kombu import Connection
with Connection(hostname=url,
ssl={'cert_reqs': ssl.CERT_NONE}, default_channel='test_ext') as conn:
result = addCall.apply_async((a, b), queue='TEST', connection=conn)
# result.wait()
conn.close()
return result
@app.route('/works', methods=["GET"])
def test1():
my_ext_caller(1, 1)
return 'test'
@app.route('/not_working', methods=["GET"])
def test2():
addCall.delay(1, 1)
return 'test'
if __name__ == "__main__":
app.run(debug=True)
File "/Users/jre/py39/lib/python3.9/site-packages/kombu/utils/functional.py", line 30, in __call__
return self.__value__
AttributeError: 'ChannelPromise' object has no attribute '__value__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 447, in _reraise_as_library_errors
yield
File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 434, in _ensure_connection
return retry_over_time(
File "/Users/jre/py39/lib/python3.9/site-packages/kombu/utils/functional.py", line 312, in retry_over_time
return fun(*args, **kwargs)
File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 878, in _connection_factory
self._connection = self._establish_connection()
File "/Users/jre/py39/lib/python3.9/site-packages/kombu/connection.py", line 813, in _establish_connection
conn = self.transport.establish_connection()
File "/Users/jre/py39/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection
conn.connect()
File "/Users/jre/py39/lib/python3.9/site-packages/amqp/connection.py", line 323, in connect
self.transport.connect()
File "/Users/jre/py39/lib/python3.9/site-packages/amqp/transport.py", line 113, in connect
self._connect(self.host, self.port, self.connect_timeout)
File "/Users/jre/py39/lib/python3.9/site-packages/amqp/transport.py", line 197, in _connect
self.sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
did you start the RabbitMQ service?
Also change the port at the top to 5672
to run rabbit in docker:
docker run -d -p 5672:5672
or if you don't have docker installed then:
sudo systemctl start rabbitmq.service
hmm
could my_ext_caller not be collecting the promise and so you don't see it's error?
I'm not 100% on the behavior of apply_async in kombu
but that implies it's returning a promise. and then you immediately close without collecting it
whereas the decorated task is actually getting the result?
so they're both failing but you only see one of them failing?
ya you never called .get() on the result from .apply_async(): https://docs.celeryproject.org/en/stable/userguide/calling.html#results-options
o nvm I missed task_ignore_result=True in that decorator
need someone who is good with cookies/requests/headers, if you can do a job for me im paying btc
dm ^
!rule 9
yeah of course, its works fine with out flask
hmm
does task.delay() ignore the ignore_result=True setting?
the documentation I linked up there implies that task.delay does not allow extra execution options
possibly including ignore_result=True
if you change delay to apply_async do you still see the error?
and/or the other way around
that's the only difference b/w the endpoints I can see
they're calling the task with different methods
it never get to that part. It was throwing this before
WARNING: No hostname was supplied. Reverting to default 'localhost'
with the .delay
I can try that in the morning - but .delay just calls apply_async.
it works out side of flask
I've always used something like CELERY_BROKER_URL = "pyamqp://user@host"
that was introduced in 4.0 i think
hmm
going to test this out in the morning - https://flask-celeryext.readthedocs.io/en/latest/
looks nice
Setting my DEBUG variable to false in django throws 500 error, i already looked at stack but setting ALLOWED_HOSTS to ['*'] does not work
i'm pulling an all nighter because i can't have debug enabled in production, any help is appreciated
pip install django-cors-headers
CORS_ALLOWED_ORIGINS = [ # your frontend addresses of the web site. I added additional localhosts for access from testing applications
custom_allowed_origin,
adding_www(custom_allowed_origin),
"https://localhost:8080",
"https://localhost:8000",
"https://localhost",
"http://localhost:8080",
"http://localhost:8000",
"http://localhost",
]
INSTALLED_APPS = [
"corsheaders",
...
gonna try, thanks a lot
MIDDLEWARE = [ # important to be first here
"corsheaders.middleware.CorsMiddleware",
forgot, plus here
i'm not using a frontend, i'm using class based views as generics @inland oak
if that makes a difference
debug your source of problem
by checking Chrome Dev Tools, console and network tab for clues
and adding a bit more log printing records to your django view
if it is CORS problem, it will be shown in console/network tab by some specific msgs, or by failed OPTIONS requests. OPTIONS are important for preflight CORS thingy
guys i have a url
http://127.0.0.1:8000/home/name/name?q=Hello
and code
q = urlparse(request_path).query
but its not working, it is a empty str any solutions?
sorry to bother you like that, but can you hop on a call? i know it's not exactly exciting, but i have been pulling an all nighter and i still am not finished. if you don't want i understand
PythonAnywhere is like a cloud for python based web applications?
What if I learn AWS technologies instead? 3 birds one stone or something?
@inland oak still not working btw
MIDDLEWARE = [
...,
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
...,
]
read the network errors for clues 
get more logging msgs to find where it went wrong
problem is logging doesn't work
i already tried it numerous times
hey
Django messages multiple tags
I was trying to pass multiple extra tags in the messages.add_message() as a list. It seemed to work fine while using render, but when I'm trying to use redirect, it passes the extra_tags as a string and I can't get my objects by indexing as it considers the whole list as a string. Is there a way to solve this or pass multiple extra tags? Here is the code-
def handleSignup(request):
if request.method == 'POST':
username = request.POST['signup_username']
name = request.POST['name']
password = request.POST['signup_password']
email = request.POST['email']
if User.objects.filter(username=username).exists():
messages.add_message(request, messages.INFO,
'Please try another username.', extra_tags=['danger', 'Username already taken!'])
elif User.objects.filter(email=email).exists():
messages.add_message(request, messages.INFO,
'An account with the email already exists.', extra_tags=['danger', 'Email already in use!'])
else:
user = User.objects.create_user(
username=username, email=email, password=password)
user.name = name
user.save()
messages.add_message(request, messages.INFO,
'Account created.', extra_tags='success')
else:
return HttpResponse('404 - Not Found')
return redirect('/')
can someone help me out with this
f = open('config.json','r+')
param = json.load(f)["param"]
@app.route('/')
def main():
return render_template('index.html', param=param)
am i doing this right
so - I rebuilt everything. I have this working in an other env. the only thing different was the python version on my systems is 3.9.9 - my server is build on docker python:3.10.2-bullseye
so down the version to 3.8.12 and works now
hi anyone saw a fastapi + dependency injection + multiple databases project?
I had an issue with my django form coming up as unbound after passing request.POST to populate its fields. my init contained an argument list, and I appear to have resolved the issue by removing the argument list and setting it to just (self, *args, **kwargs) then calling super().init(*args, **kwargs). Does anyone know why that is?
any website for good bootstrap templates?
scratch that - still having issues.
https://getbootstrap.com/docs/4.1/getting-started/introduction/ official docs should be all that is needed
how do I upload data from json file in django?
Hey guys, I'm not a web developer at all, so I apologize if this seems pretty basic but, in a website if I see:
#A bunch of code then:
</div>
<script type="text/javascript">
#a function
</script>
</div>
#end of the greater block I'm referring to in my question
Does that mean that that function only applies to the information within that greater <div> </div> block?
Post a request to the rest framework: https://www.django-rest-framework.org/tutorial/2-requests-and-responses/
Django, API, REST, 2 - Requests and responses
thanks, i will look into this
how do i upload a project to github using the desktop app
I have tried following this guide to deploy a flask application to Vercel, but still can't get it to work. I don't understand why one would have the .py-file inside the venv either.. https://dev.to/andrewbaisden/how-to-deploy-a-python-flask-app-to-vercel-2o5k
Hello,
What are thé best free courses to learn web dev with python ? ( Complete newbie in web dev but experienced with python)
If you want to try Django I kinda liked https://www.youtube.com/watch?v=Z4D3M-NSN58&list=PLzMcBGfZo4-kQkZp-j9PNyKq7Yw5VYjq9 from
Tech With Tim after that I had my own similar project in mind I built with the help of these videos and continued searching elsewhere. But Django can be little bit tricky from the beginning to get used to. And its often recommended to start with Flask I guess
Welcome to the first python django tutorial on my channel. Django is a full stack web framework that allows for rapid development of websites. In this tutorial I will be showing how to setup and install django and talk about how to navigate between different pages.
Source Code: https://techwithtim.net/tutorials/django/setup/
Playlist: https://...
In my experience, anything that's in a <script> block is global to that page, so it shouldn't matter where you put it. It might make sense to put it inside a specific <div> if the script is meant to work on that div element just so it's easier to manage
Ok thank you I'll check it out 🙂
Hi, I’m making a project and found YouTube videos that do exactly it. Is it bad to look at the tutorials and make it that way?
nvm i found it
It matters actually. Better to put scripts at the end, so your html/CSS would load first, before being stuck in long js
idk if this is the right server to ask.
is it possible to list service workers in web app?
hello i have a code , in which when i send request through postman post method is not getting called
can anyone look into this ?
https://paste.pythondiscord.com/esibepazus my code here please check here line no 45
ping me whn replying
remove the line in between
Like this
@app.route('/', methods=['POST'])
def post(self):
i tried this way only , it is not working
@cyan valley please check this
i tried this way but not worked
wait
there is no /modelTrain route in the code you sent
i tried this way ```python
@app.route('/modelTrain', methods=['POST'])
def post(self):
print('inside train post')``` then also it is not working
error?
no error i am getting
you getting error code 400. which means Bad Request
yes this is i am getting
but i am not able to understand becoz of which part of code i am getting this error?
make sure you sending json request from postman. check if content-type header is correct
see this way
now i am getting another thing
previous was fixed
found the problem. line 59. server looking for data["batch_size"] but you sending batch_size_val
you are looking for key that does't exist. either change in code or change in postman
@cerulean thicket
i tried this way python data = request.get_json() print('data=/n', data) json = ({ "status": "failed", "message": "ALL fields are mandatory" }) # in the below try catch we are accepting values from request try: country = data["country"].upper() print('country=', country) batch_size_val = (data["batch_size_val"]) epoch = data["epoch"] epoch_val = epoch except KeyError: print(json) logger.debug(json) return(json)
see this also
then also it is not working
well. only print statement debugging can help.
what data you get when print in print('data=/n', data)
data=/n {'country': 'ind', 'batch_size_val': 2, 'epoch': 10, 'epoch_val': 10}
{'status': 'failed', 'message': 'ALL fields are mandatory'}```
comment the try catch. it error out in the problematic line
Hi, I'm trying to use flask and render_template to render a table from json
the for loop i use to loop over the json does not iterate
i have checked the json it is valid
can someone assist me
{% for row in json_data["data"] %}
<tr>
<td>{{ row['col1'] }}</td>
<td>{{ row['col2'] }}</td>
</tr>
{% endfor %}
{
"count": 1,
"data": [
{
"col1": "sample1",
"col2": "sample2",
}
]
}
this is my template, and json
no iterations
when i remove try catch then it works
(o_O) okay. then try:
data = request.get_json()
print('data=/n', data)
json = ({
"status": "failed",
"message": "ALL fields are mandatory"
})
# in the below try catch we are accepting values from request
try:
country = data["country"].upper()
print('country=', country)
batch_size_val = (data["batch_size_val"])
epoch = data["epoch"]
epoch_val = epoch
except KeyError as error:
print(error)
print(json)
logger.debug(json)
return(json)
see what error it's printing
check if the loop is getting that data.
i am getting python data= {'country_code': 'ind', 'batch_size_val': 2, 'epoch': 10, 'epoch_val': 10} country= IND {'status': 'failed', 'message': 'ALL fields are mandatory'}
see in this
in this the data contains country_code and not country but somehow it printed country= IND
when i try python country = data["country_code"].upper() print('country=', country) this way then i am getting python data= {'country_code': 'ind', 'batch_size_val': 2, 'epoch': 10, 'epoch_val': 10} country= IND {'status': 'failed', 'message': 'ALL fields are mandatory'}
why it's not printing error?
on postman i am getting this
have u tried enabling debug
or reading server console
i gone throughpython <title>500 Internal Server Error</title> <h1>Internal Server Error</h1> <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>.
it's hard to debug the code in it's current state because it's failed somewhere in function.
you are using data keyword even after extracting data from it. gotta replace the use use of data variable after the first try catch and use they variables you created in the try catch.
it is not descriptive error, shown to outside world to avoid showing any sensitive info, it is useless
The only useful thing it says, that error happened at server side
which means there is somwthing which means somwthing wrong in code
can u explain in other words bhai
see this
so this
try:
country = data["country_code"].upper()
print('country=', country)
batch_size_val = (data["batch_size"])
epoch = data["epoch"]
epoch_val = epoch
except KeyError:
print(json)
logger.debug(json)
return(json)
# in the below try catch we are validating country name with country code
try:
country = pycountry.countries.get(alpha_3 = data["country_code"].upper()).name.lower()
logger.debug(f'country1 : {country}')
country = country.split()
country =("_".join(country))
logger.debug(f"country : {country}")
alpha_2 = pycountry.countries.get(alpha_3 = data["country_code"].upper()).alpha_2
logger.debug(f"alpha_2 : {alpha_2}")
except AttributeError:
jsonify1 = {
"status": "invalid",
"message" : "Invalid country_code"
}
print("invalid country_code")
logger.debug(jsonify1)
return jsonify1
try:
batch_size_val = int(data["batch_size"])
except ValueError:
jsonify1 = {
"status": "invalid",
"message" : "Invalid batch_size"
}
logger.debug(jsonify1)
return jsonify1
you see you're getting data from the data variable in first try catch so use those variables from first try catch in following try catch instead of using data variable again. it will make the code easier to work with and easier to debug.
can u use this code directly?
?
can i use above code u shared?
it's your code.
what i'm trying to say is instead of using data variable everywhere use the variable you created in the first try catch.
see in second try catch i need the variable which came in request to get country name
i am using pycountry library to to get country name , in that i need country code
you can do country = pycountry.countries.get(alpha_3 = country).name.lower() because you already created a country variable in first try catch which has that data.
i mean you don't need to do like this. this just makes the code easier to debug
let me try tjhis
issue is fixed
thank u so much. let me debug more , if i need anything can i ping u ?
welcome. you can ping me if you need any help
sure
Ah that makes sense. Thanks
Still need help?
Wait nevermind. Yeah
I have a html page with multiple input images like this:
<form method="POST">
{% for (card_path, card_name) in cards %}
<input type="image" src="{{ card_path }}" name="{{card_name}}" alt="{{ card_name}}" style="width:100%">
{% endfor %}
</form>
But in my flask app i cannot see which one of the image inputs were pressed. Normally with an input type submit you can specify the value of the button, then see what the value of the pressed button is. But it seems you can't set a value for an input type image.
How can i figure out which one of the images has been clicked?
my static directories are weird, C:\Users\[____]\PycharmProjects\the-doge-net\thedogenet/static is happening. However idk why it's doing /static, and i can't seem to find the root of the problem
Hi, when i put json["data"] on the page, its blank. nothing there. when I return the response with the template variables in flask I print the json immediately before the response and its correct
Print json in html. Like <h1>{{json_data}}</h1> check if it's there
Thats what I mean in my previous message, there is nothing. I put it in paragraph tags
but what doesnt make sense is
there other item in my json is there
there is json["data"]
but thjeres also
json["count"] which is an int
it works
Check if you are sending data to the template
data is an array of dictionaries
i mean like return render_template("index.html", json_data=data)
so yea, my return render_template is fine. I just checked and it prints to the page if you do {{ json_data }} but not if you do {{ json_data["data"] }}
json_data["data"] is the array in the json that contains the items im iterating over
I guess I'm not accessing the json properly?
or my loop
{% for row in json_data["data"] %}
{
"count": 1,
"data": [
{
"col1": "sample1",
"col2": "sample2",
}
]
}
{% for row in json_data["data"] %}
<tr>
<td>{{ row['col1'] }}</td>
<td>{{ row['col2'] }}</td>
</tr>
{% endfor %}
How can I modify this to work
the full json data prints to the page now
but cant access "data"
resolved ☑️
had to json.loads() my json instead of json.dumps() before response
funny one
thanks
https://forum.djangoproject.com/t/request-to-join-hindi-translation-team/12214 please help 😦 i cannot join the team as it shows language does not exist but it does!
Hi there fellow contributors, I wanted to help translate the Django docs, but in transifex whenever I try to join the team of Hindi it shows no language exists like that. So I wondered if you have to add me to the team. I cannot request to be added to the team either! so I am asking in this forum. Screenshot of that is attached here.
Hi I’m curious why are there classes created in the views.py file of a Django project?
They are functions that take and return web requests
Thanks. I’m trying to figure this first step. What does it mean and what am I doing?
This is from tutorial
must be new
What does the context part mean?
It should work the same way
Prolly has to do with the current thing you are editing
You can add your own implementation of get_context_data
But by default it adds the object being displayed
So I’m calling the function out when I mention m “RED” in the base.HTML file in the case mentioned above.
Well look at the comment to the side
I wrote those look
Lool
Oh yea it does so RED is a variable name to call the function
mhmm
Hey! Is there any resource that would help me to build an update system?
I mean I'm updating the github repo and app is detecting newer version it will ask user to update and eventually update the app?
I am using Flask.
I want to create a system similar to Kahoot, where one can generate a room (which will generate an ID). How can I make that room joinable by using <url>/ID
Should I generate a new HTML page for each room?
That sounds like a route thing
@app.route(“/rooms/<id>”)
def rooms():
pass
you are looking for dynamic routes. You can find many things about these online
Is there a way I could have 2 options for adding data to django models? one is manually enter the data in the fields or another option is to upload the csv file
Like a OR option type of thing?
images= cv2.cvtColor(images, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'``` how to fix this error ?
Sure, why not?
can u pls tell how?
My js code as below =
var listOfItems = ["images/dice1.png", "images/dice2.png", "images/dice3.png", "images/dice4.png", "images/dice5.png", "images/dice6.png"]
var randomNumber1 = Math.round(Math.random()*5+1)
var randomNumber2 = Math.round(Math.random()*5+1)
var dice1RandomImages = listOfItems[randomNumber1 - 1]
var dice2RandomImages = listOfItems[randomNumber2 - 1]
function winner() {
document.querySelectorAll(".img1").setAttribute("src", dice1RandomImages)
document.querySelectorAll(".img2").setAttribute("src", dice2RandomImages)
if ((randomNumber1 > randomNumber2) == True) {
document.querySelectorAll("h1").innerHTML = "Player One Wins!"
}
else if ((randomNumber1 < randomNumber2) == True) {
document.querySelectorAll("h1").innerHTML = "Player Two Wins!"
}
else {
document.querySelectorAll("h1").innerHTML = "Draw, Roll again"
}
}
winner()
And in my html code i put the js script code link near the bottom of body like
<head>
<!-- Code -->
</head>
</body>
<!-- Code -->
<script src="index.js" charset="utf-8"></script>
</body>
And there are 6 dice images so why isnt my code appearing?
I'm no Django expert but you can share your code in a help channel #❓|how-to-get-help
I’m getting a 404 error. Django tried to use URL patterns admin/ and Calc/ and didn’t match any of these. What could be the reason?
What is the main reason for 404 error?
404 not found means that the page wasn’t found
what page are you trying to get to?
Interesting I looked at urls and doesn’t seem to find no error in what I type
To a page calcs.html
Surely admin.html will work. That’s standard?
Doesn’t seem like you saved the file
Saved and retried.. same response
do you have a view for calcs/
and whats in calc/urls.py
^
Star / Wildcard imports
Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
Example:
>>> from math import *
>>> sin(pi / 2)
1.0
This is discouraged, for various reasons:
Example:
>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2) # uses sin from math rather than your custom sin
• Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
• Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
• Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.
How should you import?
• Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
• Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)
Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]
[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python
so calcs/* is supposed to go to this one thing ?
import the specific view
the urls.py for calc should be something like:
urlpatterns = [
path(‘calcs/something/‘, views.your_view).
]
you can change the import to from . import views and prefix your views in the path with views.
oh dont you need a default route
Because it seems like you are on what would be the index
And there is no index route from what it seems like
seems like empty string
path("", CalcView.as_view ... might have been right, there
put a / in the quotes
something must be fucked up with your routes then
Within command line?
wdym
trailing /
What will do follow the tutorial step by step and see if I missed anything
Sure thanks moai 🙂 and greyblue
I changed some of it like static ended with / shown in video.
I still get the ‘/‘ error
At the bottom of the page, it tells you how to do it. I think you have to change your settings file
anchor tag in html?
oh proper error web page
didn’t see the error thing
that’s only there because you are in debug mode
you can specify the error and render html templates for it in views file for the app where you wanna do that
def error_404(request, exception):
data = {}
return render(request, ‘path_to_html_file’, data)
And you have to specify them in the projects urls
You’d have to change DEBUG to false also
in urls.py: handler404 = 'myappname.views.error_404'
I'm using selenium to do a automated login, the website has cloudflare, I have bypassed the cloudflare, but when trying to get a element I feel like the website is not loading in time to get the element
[3:29 PM]
I have tried time.sleep and 'wait' in the selenium docs and both hold cloudflare would anyone have a solution for this
There are a lot of ways to wait in Selenium, what are you doing exactly? There's something like wait_for_element_clickable or something and that's usually a good way to go
But if it's really a Cloudflare issue, can't help you there
Hi ı have one question
what does new Date(userinput) do?```js
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
if(userinput==null || userinput=='') {
document.getElementById("message").innerHTML = "**Choose a date please!";
create a date object
Ok I just made a todo list app
Now I want to input a script into so when an input of an integer is entered, a calculation will be made and answer will come out. Is there resources to look at to do this?
Hiii, does anyone have any experience in making web applications on spring boot?
Sounds like a simple function. Is there something specific you are having trouble with? Might need to share a link to your code
Hi guys! I have a small project that needs like/unlike API using flask restx api. My endpoint is "/int:post_id/like". I use POST method to like/unlike a post but it is not relevent in POST (i mean we do not pass an argument in POST). Could someone give me an idea? Should i change to PUT?
It's fine to use POST https://stackoverflow.com/questions/4191593/is-it-considered-bad-practice-to-perform-http-post-without-entity-body
anyone can explain to me what flask app_context means please
with app.app_context()
I have seen this syntax first time in my life in python which appears to be C-like: print ("Second element = %d" %(a[1])) please someone explain it to me because it doesn't have a comma to separate string and format specifiers. It's weird.
firstly it has a space between print and argument, which suggests it is Python2
secondly, it has %d which makes auto conversion into integer for output
feel free to rewrite it in a newer format as
!e
a = [2, 3]
print("Second element = {:d}".format(a[1]))
@inland oak :white_check_mark: Your eval job has completed with return code 0.
Second element = 3
although I prefer f strings
!e
a = [2, 3]
print(f"Second element = {a[1]}")
@coarse torrent :white_check_mark: Your eval job has completed with return code 0.
Second element = 3
👆 f-strings
btw the info stored in a session is destroyed as soon as we leave the site right? and session is used to store sensitive info like usrname and pass , so if we click on save username and password option then is our usernme and pass stored in cookies ??
coz cookies remember the info for a long time? like a cookie with a long time to expire ?
as far as I know python frameworks use cookies as sessions
usually
i m talking about php
xD, not really the best place to ask about it
oop sorry
how can python be used for web dev?
anyone here good with flask i need help
I'm afraid we don't allow any form of recruitment here, as per our #rules.
!ban 865895424510525444 7d Upon further investigation, it seems you've already been told this more than once. Don't rejoin unless you intend to follow staff instructions and the rest of our rules and code of conduct.
The rules of our community.
:incoming_envelope: :ok_hand: applied ban to @reef cave until <t:1645957501:f> (6 days and 23 hours).
how do make organisation field compulsory and then have an option to either upload csv file or enter the data manually
I'm trying to add a table that's within a form to a <details> tag in HTML5. The table looks normal, but when I add the details tag it then causes this disaster. Any ideas?
This is python version of the format I specified?
but it is working in python3 shell as well
@inland oak @coarse torrent are both of your formats same? I am confused now.
My format is f-strings:
f"3 + 2 = {3 + 2}"
In f-strings, you can insert any expression that does not contain the same type of quotes as your enclosing string (here ") between curly braces to have it evaluated, then turned into a string via str.
The other format is using str.format():
"{:d} {:s}".format(20, "test")
In this way of using format, the letters after the colons specify how it will be displayed. Some options:
:d Number
:s String
:x Hexadecimal
:n Number, but with localized digit separators
:b Binary
:o Octal
!d str.format
str.format(*args, **kwargs)```
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces `{}`. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
```py
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
``` See [Format String Syntax](https://docs.python.org/3/library/string.html#formatstrings) for a description of the various formatting options that can be specified in format strings.
can i know why we need django or other framewark to create web applications if we can do this with javascipt and why some people use both instead of one and what's the different between them
django is a backend framework and you can use frontend JS frameworks along with it
mostly because people hate working with JavaScript afaik
and WebAssembly exists too
so it means we can use javascript in backend
and why pepole prefer python over java at backend
and can i know why we can not use python in front end
is there any way creating dynamic website using only python
well, web browsers can only read JavaScript. But, WebAssembly exists now so I guess you can create the frontend in languages other than JS
you cna probably use a preprocessor to convert python to js and back
and should we?
its a binary instruction format that allows you to create web apps in languages other than JS
ehh idk
i would still learn and use JS if you are doing any web dev'
once you learn JS though, use TypeScript instead
its a superset of JS
with type system
ok i will see
but i'm confuse right now if i should go for web development
i am beginner and know python and tkinter
also WASM supports:
- C/C++
- Rust
- AssemblyScript
- C#
- F#
- Go
- Kotlin
- Swift
- D
- Pascal
- Zig
- Grain
@mortal grotto well think about why you want to program. what do you want to make?
don't just do web dev because everyone else does it
well then do ML
so i 'm thinking first i should clear some concepts of math and get grasp at programming logic
yeah prolly
then should jump into ML and stuff
@mortal grotto Confidence comes after action, not beofre
^
if that's helpful...
python has many good machine learning libs like TensorFlow, NumPy, and PyTorch
yeah we can say
Off-topic channel: #ot2-the-original-pubsta
Please read our off-topic etiquette before participating in conversations.
oh i don't know i 'm new to discord so sry if i'm breaking any rules
you are good. just when the topic starts to veer off from the channel name/topic check yuourself
we can move to the OT channel though
and how?
!ot
Off-topic channel: #ot2-the-original-pubsta
Please read our off-topic etiquette before participating in conversations.
just press that blue thing next to off-topic channel
Hey can some suggest me content to understand rest framework in django
is developing an ecommerce website a good idea?
The page at 'https://dashboard.breadbot.me/server/744176742540771368?sidebar=levels' was loaded over HTTPS, but requested an insecure resource 'http://dashboard.breadbot.me/change/rewardadd/744176742540771368/'. This request has been blocked; the content must be served over HTTPS.
why is this happening to me when i use fetch in js?
?
class asset_inventory(models.Model):
organisation = models.ForeignKey(organisation, on_delete = models.CASCADE, null = True)
Upload_CSV = models.FileField(null = True, blank=True)
asset_name = models.CharField(max_length = 20, null = True, blank=True)
asset_type = models.CharField(max_length = 255, null = True, blank=True)
technology = models.CharField(max_length = 255, null = True, blank=True)
ports = models.CharField(max_length = 255, null = True, blank=True)
services = models.CharField(max_length = 255, null = True, blank=True)
first_discovered = models.DateTimeField(editable=False)
last_discovered = models.DateTimeField(editable=False)
status = models.CharField(max_length = 20, choices = choices, null = True, blank=True) # remove this?
def save(self, *args, **kwargs):
filename = self.Upload_CSV.url
# filename[6] += "csv/"
print("C",filename)
with open(filename, 'r') as f:
readerr = csv.reader(f)
for i, row in enumerate(readerr):
if(i == 0):
pass
else:
# row = "".join(row)
# row = row.replace(";", " ")
print(row)
''' On save, update timestamps '''
if not self.id:
self.first_discovered = datetime.datetime.now()
self.last_discovered = datetime.datetime.now()
return super(asset_inventory, self).save(*args, **kwargs)
the error is in with open(filename, 'r') as f:
How do we start with web dev
I've got a question, I am creating a "program" wich tells you if ur password is strong or not, just a simple program but I'd like to combine my python low skills with my HTML low skill, how can I create an interface in HTML for my python project?
The page at 'https://dashboard.breadbot.me/server/744176742540771368?sidebar=levels' was loaded over HTTPS, but requested an insecure resource 'http://dashboard.breadbot.me/change/rewardadd/744176742540771368/'. This request has been blocked; the content must be served over HTTPS.
why is this happening to me when i use fetch in js?
it looks like you haven't saved this picture or whatever it is in media file or maybe you made a typo in directory
Can I please have a pytest guide?
Q(topic__name__icontains=q),
Q(name__icontains=q),
Q(description__icontains=q)
)```
why is this not filtering by description and name??
Hi I tried to deploy an app and I received a “no matching host key type. Their offer: ssh-rsa” error. Any ideas what I should do?
hello i want to know what does it mean the word "contexts" in flask or python
It means it’s related to what’s currently happening.
The definition of context in the dictionary is: the circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood and assessed.
I've got a problem with some code. https://jsfiddle.net/szho6p1d/
Trying to select an element but not an inner element with :not() but it doesn't seem to be working
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
basically this is how I would want it to work
Seems like a simple task, but I'm not sure what I'm doing wrong
thanks this was helpfull
anyone know how i could store user data with a post request on nextJS?
why is this error coming while adding a django model data
class asset_inventory(models.Model):
organisation = models.ForeignKey(organisation, on_delete = models.CASCADE, null = True)
Upload_CSV = models.FileField(upload_to ='csv', null = True, blank=True)
asset_name = models.CharField(max_length = 20, null = True, blank=True)
asset_type = models.CharField(max_length = 255, null = True, blank=True)
technology = models.CharField(max_length = 255, null = True, blank=True)
ports = models.CharField(max_length = 255, null = True, blank=True)
services = models.CharField(max_length = 255, null = True, blank=True)
first_discovered = models.DateTimeField(editable=False)
last_discovered = models.DateTimeField(editable=False)
uploaded = models.BooleanField(default=False)
status = models.CharField(max_length = 20, choices = choices, null = True, blank=True) # remove this?
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.first_discovered = datetime.datetime.now()
self.last_discovered = datetime.datetime.now()
super(asset_inventory, self).save(*args, **kwargs)
print("F", self.Upload_CSV == None)
if self.Upload_CSV != None:
filename = self.Upload_CSV.path
with open(filename, 'r') as f:
readerr = csv.reader(f)
for i, row in enumerate(readerr):
if(i == 0):
pass
else:
print(row[0])
asset = asset_inventory.objects.get(id=self.id)
print(asset.id)
asset.asset_name = row[0]
print("C", asset.asset_name)
asset.save()
return super(asset_inventory, self).save(*args, **kwargs)
use something like flask or fast api (python frameworks)
first learn html css , then learn vannila javascript, then some javascript framework like react or vue
for the first step I would recommend making some random websites ideas like online shop, streaming platform etc..
with just html and css
and then make some simple projects like calculator or todo with javascript (also using your skills with html and css)
to learn anything first just watch videos on youtube, when you are experienced enough you can try reading documentation
?
I mean in python
I came here to ask this exact question and it's already been answered lol thankss
guys i need help desperately
when i fetch an api with js how do i return the result of the fetch
mine's returning the promise object (telling me that it's pending)
Sounds like you need to check the docs for the specific API you are using
is there a way to tell django not to load fixtures when testing
it's literally taking too long to load for every test
Using flask, how can I display Yes and No instead of True and False for boolean values on the site?
booleans can only be True or False, so not sure
Whatever you are returning True or False on, prolly return Yes or No?
Anyone know how to update a Bokeh plot in a Flask app without redrawing the whole plot figure? https://stackoverflow.com/q/71200659/1084875
See the section on fixtures in test cases. You can specify to load certain fixtures, or none at all
I have a form in Django like this and all these SELECT inputs are overflowing the width of my table layout.
I'm just using the form.as_table in Jinja.
This isn't exactly Python Web Dev related (more of Front-end issue)
Do I have to loop across the form fields and specify the max width something like that? Any help is appreciated.
Hey guys , Im trying to create 2 models in which you can post images and comment on them
'''
class Pizza(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True)
title = models.CharField(max_length=50)
image = models.ImageField(null=True, blank=True,upload_to="images",default="white.jpg")
description = models.TextField(null=True,blank=True)
likes = models.IntegerField(blank=True,null=True,default=0)
dislikes = models.IntegerField(blank=True,null=True,default=0)
def __str__(self):
return str(self.user)
class PizzaComment(models.Model):
post = models.ForeignKey(Pizza,on_delete=models.CASCADE)
user = models.ForeignKey(User,on_delete=models.CASCADE)
comment = models.TextField(null=True,blank=True)
likes = models.IntegerField(blank=True,null=True,default=0)
dislikes = models.IntegerField(blank=True,null=True,default=0)
def __str__(self):
return str(self.user)```
my models.py
class PizzaCommentCreate(CreateView):
model = PizzaComment
context_object_name = "comment"
template_name = "sky/pizzaCommentCreate.html"
fields = ["comment"]
def get_success_url(self):
return reverse_lazy('pizza')
def form_valid(self,form):
form.instance.user = self.request.user
return super(self,PizzaCommentCreate).form_valid(form)
my problematic view
path('PizzaHub/',PizzaList.as_view(),name = "pizza"),
path('PizzaDetails/<int:pk>',PizzaDetail.as_view(),name='detail'),
path('PizzaCreate/',PizzaCreate.as_view(),name = "create"),
path('PizzaUpdate/<int:pk>',PizzaUpdate.as_view(),name='update'),
path('PizzaDelete/<int:pk>',PizzaDelete.as_view(),name="delete"),
path("PizzaCommentCreate/",PizzaCommentCreate.as_view(),name="commentCreate")
the urls
this is the error message
im kinda stuck if anyone has resources or advice it would bee really cool
Django btw
Using Flask, how can I toggle between asc and desc using /sort ?
@app.route('/sort')
def sort_list():
places = Place.query.order_by(Place.name.asc()).all()
return render_template("index.html", places=places)
It doesn't quite work if i just set all to []
also its rather tedious doing this for all tests
isnt there a way to set default no fixtures
you can use GET parameters and pass either "asc" or "desc" when calling the endpoint, something like /sort?by=asc and then retrieving the value of by
You maybe can try out SimpleTestCase or TransactionTestCase? If you’re careful using them your tests will run much faster since it won’t recreate the entire test database between tests. However this means you have to be more careful not to introduce contamination of state between tests
guys, can anyone here help me solve this error?
TypeError: The view function for 'slow' did not return a valid response. The function either returned None or ended without a return
statement.
i'm using flask
at that point i could aswell go over to pytest
True. Also could consider writing your own Django test runner. It’s not incredibly hard, and you can achieve your exact desired behavior if the default options aren’t doing it. https://docs.djangoproject.com/en/4.0/topics/testing/advanced/
might be handy for v2, doe v1 is almost at its EOL
so rewriting tests is not worth the effort
thanks for the reference doe
is rhere anything similar to this for django
Run Python scripts from Node.js with simple (but efficient) inter-process communication through stdio. Latest version: 3.0.1, last published: 4 months ago. Start using python-shell in your project by running npm i python-shell. There are 202 other projects in the npm registry using python-shell.
i want to build a leetcode clone of sorts but im not sure how i can go aboit running submissions
Uhhh do you care if the result is secure
Because if no, you can just use ‘eval’ on strings your users submit. If yes, then you’re in for a large amount of complicated engineering effort
not gna be using this for anything other than tht
oh wtf
i can eval
a whole python script?
As long as it’s valid in the current namespace
Or you could write the script a user submits to a temp file, then run via subprocess ‘Python temp file.py’ and capture the output
itd actually work?
ohhhh
alr i'll put that into thought
that seems like an idea
alr tyty
can eval run functions or is thst not a thing
i dont have my editor with me rn :(((
If you look into the documentation detail, looks like it depends. https://docs.python.org/3/library/functions.html#eval
See the section on “nested locals”. Executing a tempfile may be a more general solution
hmmm i see
maybe the tempfile is the way to go
is it difficult to run a subprocess
im new w django and i honestly have no idea what im doing
No. It’s in the Python standard library: https://docs.python.org/3/library/subprocess.html
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> i am having this error while deploying fastapi in a docker
how do i add data from csv file to django models?
I have created a function to read the csv file
fetch(`/change/rewardadd/${format}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify({newValue: {level: levelint, role: roleid}})
});
The page at 'https://dashboard.breadbot.me/server/744176742540771368?sidebar=levels' was loaded over HTTPS, but requested an insecure resource 'http://dashboard.breadbot.me/change/rewardadd/744176742540771368/'. This request has been blocked; the content must be served over HTTPS.
why is this happening to me when i use fetch in js?
Does anyone knows about website making ?
Who can help me with smoke test in django rest framework?
I have an application that runs asynchronously to my uwsgi app. Though when I hit the root directory, I want to be able to pull certain stats from that app (on the same system). What's the best way to implement this?
Would this be an instance where BaseManger would work?
im trying build search functionnality in my django app i installed django filters but when i go to add it to installed apps i get : ModuleNotFoundError: No module named 'django_filterrest_framework'
Awesome I created ssh key and I see it in my user ssh file.
I did git push heroku master but I still get a “no matching host key type found”
@native tide what's the question? Just because you add a key to a repo doesn't mean it's used. You need to load and call it.
Hi. I have beginner experience in html/css + javascript. wanted to learn python and unfortunately have to make a website + a mobile app - what language would you guys recommend for the front-end?
I'm going into ML hence needing to use Python, but I've heard linking Python to html is not a good idea. I'm also not sure what the best lang would be for mobile dev w/ Python
I'm also going to incorporate NLP and an ML algorithm I don't know yet if that influences the recommendation at all
How would I load and call it?
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/bin/gunicorn", line 8, in <module>
sys.exit(run())
File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 67, in run
WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 231, in run
super().run()
File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 72, in run
Arbiter(self).run()
File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 229, in run
self.halt(reason=inst.reason, exit_status=inst.exit_status)
File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 342, in halt
self.stop()
File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, in stop
time.sleep(0.1)
File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld
self.reap_workers()
File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
raise HaltServer(reason, self.WORKER_BOOT_ERROR)
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I am trying to run fastapi in docker but i am getting error. I am using docker run -d -p 8080:8080 onetest to run the container. I was unable to rectify this error. When i run the application without docker locally i am not facing any problem. I am having this problem with running fastapi with docker.
bind = "0.0.0.0:8080"
workers = 4
timeout = 300
worker_class = "uvicorn.workers.UvicornWorker"
``` gunicorn_config.py
need help with django rest framework
i have a player model in which there is data of players including country they belong to
i have to create an api with return players grouped by country in json
{"japan":[list of player],"taiwan":[list of players]}
how can i create a serializer which can do this
https://www.django-rest-framework.org/api-guide/relations/ read about fifty shades of nested serializations
Django, API, REST, Serializer relations
hey
i taught myself python
and wondering about web dev
do i need to get my hands into html, css, js or any other framework
Hey @native tide!
It looks like you tried to attach file type(s) that we do not allow (.pdf). 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.
also if you know the book beloiw is good or not
"Web Development with Django by Ben Shaw, Saurabh Badhwar, Andrew Bird"
I'm making an api using drf and using session authentication for the endpoints. While testing the PUT request I noticed that the url was making 5 queries. 1 of them was duplicate.
1. SELECT `django_session`.`session_key`, `django_session`.`session_data`, `django_session`.`expire_date` FROM `django_session` WHERE (`django_session`.`expire_date` > '2022-02-22 10:02:16.956277' AND `django_session`.`session_key` = 'y4o67bixcdql4slxtjq2d9yfkp11xm8s') LIMIT 21
2. SELECT `accounts_baseuser`.`id`, `accounts_baseuser`.`password`, `accounts_baseuser`.`last_login`, `accounts_baseuser`.`is_superuser`, `accounts_baseuser`.`first_name`, `accounts_baseuser`.`last_name`, `accounts_baseuser`.`is_staff`, `accounts_baseuser`.`is_active`, `accounts_baseuser`.`date_joined`, `accounts_baseuser`.`email`, `accounts_baseuser`.`id_number` FROM `accounts_baseuser` WHERE `accounts_baseuser`.`id` = 1 LIMIT 21
3. SELECT `accounts_baseuser`.`id`, `accounts_baseuser`.`password`, `accounts_baseuser`.`last_login`, `accounts_baseuser`.`is_superuser`, `accounts_baseuser`.`first_name`, `accounts_baseuser`.`last_name`, `accounts_baseuser`.`is_staff`, `accounts_baseuser`.`is_active`, `accounts_baseuser`.`date_joined`, `accounts_baseuser`.`email`, `accounts_baseuser`.`id_number` FROM `accounts_baseuser` WHERE `accounts_baseuser`.`id` = 1 LIMIT 21
4. SELECT (1) AS `a` FROM `accounts_baseuser` WHERE (`accounts_baseuser`.`email` = 'test@email.com' AND NOT (`accounts_baseuser`.`id` = 1)) LIMIT 1
5. UPDATE `accounts_baseuser` SET `password` = 'pbkdf2_sha256$320000$9RfVbFcF0TMLB9CY8beowq$J5DuRZEXAvzC21T7u7AtHf9UQCsMW8R63shQQg/ePkY=', `last_login` = '2022-02-22 10:02:16.947069', `is_superuser` = 0, `first_name` = 'Test', `last_name` = 'Update', `is_staff` = 1, `is_active` = 1, `date_joined` = '2022-02-22 10:02:16.539777', `email` = 'test@email.com', `id_number` = '111111' WHERE `accounts_baseuser`.`id` = 1
I used RetrieveUpdateDestroy api view for the endpoint.
class UserView(RetrieveUpdateDestroyAPIView):
permission_classes = [IsAdminUser]
queryset = models.BaseUser.objects.all().order_by("id")
serializer_class = serializers.UserSerializer
Could anyone know why it would execute the same query twice? (2 & 3)
hey guys me and my friends re making a web application, if anyone interested pls dm me personally. we originally need people who are good at Html5, CSS, Python and anyone good at vue.js framework(this is not a paid job, no one is getting paid)
It says there is a problem with the package, so look into that. Also, you want to use a virtual environment... in addition to protecting.yourself from other disasters, it may potentially resolve the error
Can anyone tell me best resources to learn django?
lmao if u wanna be a web dev use js and actual web dev languages
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
You’ll need to filter it to web development and look for the ones on Django
documentation, books like "Django in examples" and practice
i have this model field with 3 choices
how do I display all those 3 choices on the client side and also let them update it?
how old is too old for a backend package? For instance, flask-login hasn't had a single commit for the last 8 months. Is that bad?
i have a slightly dumb question -- I am just getting started with django and have built a basic blog with a login, registration, password reset, etc. I'm really enjoying the django interface and would like to use it as my back-end for a web app. I will likely be using React for the front-end design.
However, when someone goes to my website, I want it to first have a typical marketing approach: homepage, about us, FAQ, about us, etc. Then the subscribe/login/get started attached.
For those who have built web apps, but also have a project site built like a regular website -- do you still use django for the whole thing? Or do you, for example, build the site separately and then have it link to the web app django project when users register and login?
For either option: What would you recommend?
Front can be made completely in react, Vue, angular
While still having fully functional Django backend working as REST API in JSON format to input and output data
Django, API, REST, Home
No problem to link custom login form from react to Auth in Django
Thank you!
So build the company site using traditional front-end tools.
Build the app using a mixture of Django and Django React?
Have the company site run from the rest APIs?
(sorry new to django rest, so only have a limited knowledge of it so far but pulling up some tutorials and that site)
What is Django react
whoops, meant django rest
Not getting last question too
need another coffee lol
Django rest is modification addition on top of regular Django.
Original Django is fully available during Django rest usage
pls tell how to do this?
Like this? @inland oak Roadmap:
Create project using Django + Django React API ▶️ Build web app inside django project
Using the same back-end, build the company site within the project under its own separate folder directory to hold css templates, pages, etc
ahhh ok
So you create a django project as usual, then essentially add django react on top of it -- or integrate it
Yes
ik this is dumb but anyone know how to get a discord server id using a api if you know the api pls tell me
can you build an api with regular django and use react or do you NEED django rest? Asking because I can hook up a react app with base flask and not use the flask_restful package.
Then Django Rest API takes care of the hooks to essentially link the company site with the web app as one functioning environment?
You can build API with regular Django, it is just harder.
Django rest is a package of ready out of the box solutions, that make it by magnitude simpler
ik this is dumb but anyone know how to get a discord server id using a api if you know the api pls tell me
Not really getting question
oh ok thats cool to know thanks
Explain simpler
@inland oak can u take a look at this..?
I'm probably missing a few crucial pieces of information in order to ask the right question. I'll do some research! Do you have a recommendation for a good Django Rest API walkthrough similar to what Corey Shafer does on youtube?
django-rest-framework has pretty great documentation on setting up REST APIs in django
see @inland oak 's link above
I hate YouTube learning.
I think official quickstart tutorial is a good to go. And docs are good there in general
There is even a book
brilliant, thank you both!
YouTube learning is a waste of time to me
Really bad quality and full of water
Docs and books are superior by magnitude
Agree with books for sure, I finished automate the boring stuff recently and loved it.
Thanks again for your time.
import * as React from 'react';
import { Text, View, StyleSheet, Button, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';
import { useState } from 'react';
export default function App() {
const [subtotal, setSubtotal] = useState(0);
const [numDiners, setNumDiners] = useState(0);
const [tipPercentage, setTipPercetnage] = useState(0);
const [result, setResult] = useState({});
const styles = StyleSheet.create({
screenContainer: {
flex: 1,
justifyContent: "center",
padding: 16
}
});
const submit = (e) => {
e.preventDefault();
if (+subtotal <= 0 || +numDiners <= 0 || +tipPercentage <= 0) {
return;
}
const total = +subtotal * (1 + +tipPercentage);
setResult({ total, totalPerDiner: +total / +numDiners });
};
return (
<div className="App">
<form onSubmit={submit}>
<fieldset>
<label>Subtotal: </label>
<input
value={subtotal}
onChange={(e) => setSubtotal(e.target.value)}
/>
</fieldset>
<fieldset>
<label>Amount of People Sharing Bill: </label>
<input
value={numDiners}
onChange={(e) => setNumDiners(e.target.value)}
/>
</fieldset>
<fieldset>
<label>Tip Percentage: </label>
<select
value={tipPercentage}
onChange={(e) => setTipPercetnage(e.target.value)}>
<option value="0">0%</option>
<option value="0.05">5%</option>
<option value="0.1">10%</option>
<option value="0.15">15%</option>
<option value="0.2">20%</option>
</select>
</fieldset>
<View style={styles.screenContainer}>
<Button title="Calculate Tip"
type="submit"
onPress={() => this.handleButtonPress()}
/>
</View>
</form>
<p>Total Amount: {' $'} {result.total && result.total.toFixed(2)}</p>
<p>
Total Per Diner:{' $'}
{result.totalPerDiner && result.totalPerDiner.toFixed(2)}
</p>
</div>
);
}
could anyone help me figure out why my button wont submit the form?
I don't think you need an event handler from on your button
also is this.handleButtonPress defined somewhere?
what is that
I'm supposed to make this look better..
https://thewebdev.info/2021/01/26/create-a-tip-calculator-with-react-and-javascript/
I honestly don't know what I'm doing so I need to go learn some stuff haha
Spread the love Related Posts Create a Tip Calculator App with Vue 3 and JavaScriptVue 3 is the latest version of the easy to use Vue JavaScript framework that… Create a Tip Calculator with Vue 3 and JavaScriptVue 3 is the latest version of the easy to use Vue JavaScript framework that… Create a Counter […]
try using the button without onPress
Nothing happens when I click it
Try this.
- use a custom hook to handle input
const [value, setValue] = useState(initialState)
function handleChange(e) {
setValue(e.target.value)
}
return [value, handleChange]
}```
- Use the custom hook like this
const [name, setName] = useInput('')
- In the form fields
onChange={setName}
just make sure you have your button as type="submit in the form
I don't think you need to handle onClick directly for submit buttons
I could be wrong though
in your onSubmit
const dispatch = useDispatch()
const onSubmit = (e) => {
e.preventDefault()
const obj = { name, ... } // Your states
dispatch(yourFunc()) // if you're using redux you'll need to use useDispatch
}
I will try this, thank you so much!
just seen you aren't using redux. You don't need useDispatch() but I'd suggest you read on how to use react-redux for state management. Traversy Media has a really good tutorial on it. If you run into any problems you can DM me. Happy hacking!
Replace the dispatch() with your functions
Appreciate the help!! We are using react native without knowing html, css, js, etc.. So I really need to learn a lot lol. My teacher is learning as we go too and she just finds articles online for us to do lmao. College 🙄
Welcome to adulthood 101. We're all winging it
real world experience lol
Hola, since you're Web Devs^^ i think you could help me with a Webscraping problem
Does someone of you know if it would work, when i load the Values of my Mozilla Cookie into my Script and then run the same Webpage with that Script?
Because i'm struggling with a JS Login on my Python Script and i thought that could be one way, but i havent tried it and nobody could tell me if it would work
anyone worked with ajax?
you mean jquery $.ajax()?
Can someone point me to some good resources for web dev/hosting?
I am writing a custom migration in Django. In my operations, I first have an AlterField and second a RunPython which also has a function for reverse_code. When Django reverses this migration, does it run the RunPython operation first?
The AlterField is adding a unique constraint. When I revert the migration, I get a unique constraint violation from my RunPython. Thus, it seems RunPython goes first, but it relies on the unique constraint being removed before running.
I may try to split AlterField into two operations - one that allows nulls and another that removes the constraint. Then my RunPython should be able to go between I think. Not sure if there is a better way.
What does the the RunPython command do? nvm actually read the snippet
But anyway in my experience Django does run the migration operations in the order listed, and in reverse order when running a reverse migration. So I think what you proposed makes sense.
Thanks. It turns out I would have had to split it up anyway for other reasons.
I needed to implement this as well https://stackoverflow.com/a/1934764 and as per the comment, I need to set null=True and change the field type separately. So I can just apply the null constraint when I change the field type. This has worked for me.
I am kinda good at flask I know how to use it but I want to know about backend web dev and indepht
what should I learn?
Backend in depth, is about learning code quality at extreme level enough to maintain in a clean way large code bases
So, it begins from
System analysis and design to plan your backend
And continues with
OOP, Design patterns, clean code, TDD, DDD and different Robert Martin books
Optionally getting to know Infrastructure as a code at least at minimal level or higher
Because backend is quite merged with DevOps/infrastructure
CI CD is included into it
CI/CD
you should also know how to make APIs, use cloud services, mess with databases, linux proficiency, etc
wdym by oop
I'm good:
clean code
need to learn more:
design
design patterns
to learn:
system analysis
tdd ddd
OOP, polymorphism, inheritance
SOLID and etc.
U can consider it is being prerequisite to learning design patterns
I would recommend to try making priority and learning unit testing first then
It makes biggest jump in code quality, by ten times
And with minimal effort
@warped kernel this is pinable

I'm not gonna make a call on that, since I'm never active in this channel and not very informed on web development. Link to the message in #community-meta and ask for it to be pinned, and someone more knowledgeable can make the call.
alright!
Just to clarify, unit testing book is a prerequisite to TDD
That is exactly how I describe my adventures for the last 1.5 year
Can someone recommend an API documentation solution (for Django) that comes with code examples? I don't like Swagger UI nor ReDoc
Sphinx
It is universal documenting tool for Python, that as a result compiled into static html,CSS,js files
Not just for APIs
I'm looking for an API one
That doesn't look like absolute garbage like that does
Stoplight is what I'm considering currently, just trying to see what people are using
(a lot of big names use that so it's promising but still looking for alternatives just in case)
yes
Just use fetch
Probably
Selenium is the ultimate web scraping answer
Fitting to be used as a heavy artillery against any type of problem
At the cost of higher CPU and RAM consumption
Be lazy, steal it from bootstrap
And? Bootstrap can be still used
If u need range spider
Or I did not understand what do u mean by range slider
Looks like regular slider
Which u can implement
With any frontend means.
On your own
Or by taking from bootstrap
It would be easier to implement custom slider in frontend framework
But bootstrap should work in backend as alternative
Or any other CSS framework
Mine too
So what is the problem then
And
Already told you how to create in Django
I have a feeling like u a just missing html/CSS/js basics
Perhaps to read it first
Then learn js
I am lazy to read your code.
I can just say that general idea what u need to do in
Making slider custom or bootstrap.
Attaching yourself with JavaScript event to listen to value of slider changes or drop down mouse thing to finish.
When necessary event happens, u fetch/Axios whatever js request to your API.
Using data u update DOM values.
Client side in backend is painful, u should consider making just post request with full rerender of page (instead of js requests)
Or it can be done in a nice way with frontend framework, which should be needed here to scale the code
U have an option to make it almost without js by just making post request for full rerender, but this solution is bad because requires full page rerender
And it will be just bad to scale
In reality you need frontend framework here, like react/Vue to make it beautifully easy
It will be brain dead simple to implement there
U can implement what u wish with just vanilla js/jQuery but in my opinion those tools should not be used in 2022 year unless absolutely necessary
U will need to learn vanilla js anyway, in order to understand what u a doing in frontend framework
At limited level sufficient to use frontend framework for small projects
I implemented https://shapevpn.com
ShapeVPN provides WEB GUI to install Wireguard as a self-hosted VPN to Ubuntu 20.04 server.
With Vue.js and Django as rest API
I used opensource VPN protocol wireguard under the hood
Has anyone worked on augmented reality ? I need some help
ok
Hi guys. What are some free ways to host a static website? If any.
github pages
Netlify
But the domain cost money
message2 = render_to_string('email_confirmation.html',{
'name': myuser.first_name
'domain': current_site.domain
'uid': urlsafe_base64_encode(force_bytes(myuser.pk))
'token': generate_token.make_token(myuser)
})
is here any syntax error..?
we can add gitlab pages in addition to github pages then 😉
Is it possible to keep everything at 0$? I’m not good with money stuff irl. And I want to do this to show off to employers
as long as it is just static website, yes
if it will be python application? it would be more challenging.
It would be a Python application. With HTTML and CSS
Why is that more challenging?
because python application can't be served as static files
you need to use Linux machine instance or some sort of bastardized python application service like Heroku
AWS gives free Linux instance to use up to 1 year from your first registration
I have a Linux machine virtualized? Also I think my friend used Dockers to do hers.
you can serve from it
Well. I guess my virtual machine can’t serve yeah
I see. I guess it’s Heroku or GitHub pages then?
I am trying to make a website called quipswap. Basically the functionality is that you can create a quip which is a small image and you can send that to someoen on your friends list, so basically in the app, everyone has a list of quips they created, a list of quips they can see because it was shared to them, and a page to make a quip
how would I set up the database for this?
https://ngrok.com/pricing in theory ngrok can be used as workaround to demonstrate application served at your local machine
ngrok secure introspectable tunnels to localhost webhook development tool and debugging tool
while your machine is online
AWS/Google/Azure, all of them give general long term free instances to use for some time
Google for half of a year
AWS a year
Azure dunno
the page to make a quip would allow them to add an image, and a multiple select element to select the friends they want to send the quip to
I guess my game plan is to set everything up on Flask and make sure it works before going to one the previously mentioned?
If possible Darksind can I DM you about this? I don’t want to keep talking about it because others want to post there questions
I don't do DMs, ask here
DMs are quite rude to other people's time
when you ask in public, you are answered by any willing free person that has time at the moment
with DM you are occupying and pestering particular person
Sorry Dark. I’m still getting used to the world
But anyways. I think I’ll keep working on my flask
Ask right questions, you will get the answers 😉 Nice of you at least to ask before trying DM
And then maybe pray I can get something going with one of the pre IOU’s let mentioned things
ok so I'm working on a website that allows for users to share images to people in their friends list, the functionality to share images, is that you have a form that takes in an image and you have an element where you select all the friends you want to share it with.
how would I store this in the database so for any given user, I can query all the posts that they have created and all the posts that have been shared to them
example:
Table user
Record: name
Table images
Path to where it is stored
Foreign key to Author
Table sharing_links
Foreign key to User Author
Foreign key to User target
Foreign key to image
So One user has access to images, which
SELECT images from Table images where Author ID = Their ID
and union with
SELECT images in (SELECT shared_links image IDs, where User Target = Their ID)
Feel free to create any other alternative schemes, that's just as first suggestion
ok wait, so just to be completely clear, when we are creating the form to create a post, we would have to create sharing links for each user selected
so if I created a post and shared it with 3 friends, we would have to create three sharing_links "objects" if you will
yes
Feel free to send Queries in Bulk method, so you could send it in one request to database instead of multiple ones
Helpppppp!
If someone click on button so the page refresh and give another button without changing the url
im trying to add search functionality to my django backend i have 'django_filters' in my installed apps and i keep getting this error ModuleNotFoundError: No module named 'django_filters'
In flask
Anybody?
How we can identify user devices for every login and for new device send alert as google do
How we can identify user devices as google do
if we do log in with a new device, then google sends an email alert..
I am using custom login with email/password
I tried user-agent but that is not working..
I want to save the user device in DB and every login wan to check the device if same that is ok or if new then will send the mail
Any suggestion/example
I am using flask for my all APIs
Hey guys! I'm working on a simple API to learn how to work and develop it. This is a no-name restaurant order and I'm not sure how to build the json array correctly:
"products": {
"product":{
"_id": "asdf1",
"name": "Burger menu",
"addons": "",
"price": 12.99,
"currency": "EUR"
},
"product":{
"_id": "asdf1",
"name": "Chicken burger",
"addons": "Spicy sauce",
"price": 6.99,
"currency": "EUR"
}
}
}```
For sure I have duplicate `product` key in here + how could I get all prices from here to sum it up?
I have idea for products
{
"products": {
"ids":
{
"asdf1",
"asdf2",
"asdf3"
},
}
}
But I'm not sure how to add here the rest of the details like name, price etc in here
Hi! I'm trying to learn Flask so I've been playing with it and reading about the last couple of days. Now I'm doing a personal project to get my hands dirty. My ideas is to make something similar to smallpdf.com. A site that lets you upload stuff, process it, and then serves it back.
I can already let the user upload the files and I know how to serve them, but I’m wondering if I’m building it in the correct way.
My idea was to give the user a session id so I can serve them back their own processed file and not mix them up (if someone else is using the webapp at the same time) then deleting both files so as to not run out of space.
I wonder if anyone has a video or a guide that builds a site kinda like that so I can compare. I feel I would build it in a way that’s not flask-y
I don't know if I can link to a pastebin to give a better idea of how I've been building it so far
How i make button which refresh page and give a new button without redirect in flask
maybe u need to use AJAX..
Whats that know i was thinking i can do with post method if u know pls dm me
i also don't know much but u can look more about ajax
it may do the work which u need
But the ajax is javascript language but i know only python
You need javascript to do what you want.
I know that but jinja also do the same work
hi guys, quick question: how do files get uploaded to s3? Im using django storages and facing problems uploading large files. do the files go to the server first them s3? or directly from client to s3?
the thing is, S3 bucket has SECRET auth that only your server can auth
So obvious thing to do would be, uploading to server first and from it to S3 bucket
But at the same time, this creates doubled traffic and the biggest concern about it is TRAFFIC LIMITS which are charged for you
I know that DigitalOcean is not charging for transfers to S3 bucket from servers located in the same LOCATION as S3 bucket
which eliminates the problem
could someone help me create a flask application which can be used with a tensorflow/keras model
Love DO.
Not exactly Python-related, but does anyone know of a trutstworthy ad-blocker extension?
i use Ublock Origin, works good
for super sensitive stuff I operate without all extensions in incognito pages just to be sure though
Alright, thanks.
guy's can u please check my project - https://github.com/Carti23/Ecomm-DRF/blob/main/README.md it's fot the resume (junoir position)
i need to run this flask code:
import flask
from flask import *
app = Flask(__name__)
@app.route("/")
def index():
return "hello"
on my network so i can go to this from my phone for example when i run this command:
flask run -h 0.0.0.0 -p 80
its not working on my phone but it dos work on my own pc why is that ?
please help me
hello
not sure this is the best channel for this question, but:
I'm trying to retrieve the url to an image from the COCO dataset (for instance, https://cocodataset.org/#explore?id=216739)
the issue is that this image is loaded dynamically/takes a while to load (javascript? dunno!);
I've tried using urllib and requests, but cannot get the HTML with the full content (or, at least, the url of the image, http://farm3.staticflickr.com/2794/4190008256_fb66764971_z.jpg)
I've checked for solutions online, nothing worked; I don't want to use selenium
suggestions?
You run your flask app localy on your pc and it is not visible to anyone in the internet
its on host 0.0.0.0 so it needs to be visible to all Devices that Connected to the network that my computer is connected to
How do you try to access it from phone
Why don't you want to use selenium? This is the tool for the job.
unnecessarily complicated for what I need
I'm able to use the cocoapi that has been written in Python, but for that I need to download a 240MB ZIP file with the image annotations
unfortunately they didn't write an API where I can simply input 'image ID' (an integer like 216739) and get the image back
I also saw that the package 'requests-html' exists... but not for Windows
How do I change text in a HTMl file after I already rendered the template in flask?
like if i render template, how do i change the text in it after 5 seconds for example
hi
ok question
if I pass a multiform data to a python backend
(like this react example)
const createUploadForm = () => {
console.log('value of uploadFile: ', uploadfile)
var formData = new FormData();
formData.append("image", uploadfile)
const obj = {title: postcomment.title, content: postcomment.content}
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
formData.append("document", blob);
return formData
}
useEffect(()=>{
var formdata = createUploadForm()
if(postcomment.submit){
// axios.post(
// "http://localhost:8000/lightone/comment/1/",
// {title: postcomment.title, content: postcomment.content}
// )
axios({
method: 'post',
url: "http://localhost:8000/lightone/comment/1/",
data: formdata
})
how would I decode this on a python backend?
there are a bunch of mediocre solutions I found on the net that might work, but there should be a straightforward solution
is there anybody here?
django
im using django
whats the answer
im not going to use that
i want to parse an incoming form
there is absolutely no reason to need a framework on top of another framework
zero
Jquery does the job..although you can also check node.js or react
my room light dashboard
are you using flex or grid?
looks like grid
Selenium is pretty easy to use, dude, and I can tell you from experience that it will definitely work. If those other methods don't work for you, then it is not unnecessarily complicated.
I think it needs more side padding and some gap
but otherwise it looks fine
maybe a single submit changes button for all the buttons?
A REST API doesnt necessarily have to return a response in json?
A REST API could also return response in XML?
yes
Technically yes, but at this point rest is pretty synonymous with JSON over http
Yeah that's what I thought too that JSON is synonymous with REST.
We utilize a third party API and they said they were changing API from SOAP to REST and I was relieved that I wont have to deal with XML anymore. I can directly with json. I made request to their new API and it still returns XML lol.
But I understand a lot of people have XML in their codebase, so they likely didnt want that to get effected.
If someone said they were moving from soap to rest but still had most everyone returning xml I would feel thoroughly cheated
I feel cheated by json. lol. https://htmx.org/essays/hateoas/
I dont know why I never thought of this before, but XML looks a lot like HTML.
just knowing how to work with networking protocols (TCP, UDP, HTTP, etc) and sockets would get you 80% of the way there
I'm new to python web development. How would I make a input, so they can input a string, send it to my server, and I return the string, after processing it with my already written code to modify the string?
Any good basic tutorial on FastAPI or Flask should cover what you need to get started
If you only need to process one string at a time, a single GET endpoint should do
Totally depends on the planned design/functionality to implement
Is it going to be one page of content, with something like 4-5 blocks of unique stuff? All right, possible.
Is it going to be 2 pages, out of 2-3 blocks? All right still possible
It has 6 pages with 2 blocks
it depends on originality of CSS layout
if blocks are reusing same CSS, then they can be considered as the same
we count only UNIQUE CSS blocks
blocks with same applied CSS, can be not counted
if you have 6 pages with 2 blocks out of ALL of them UNIQUE. You are highly likely will not be able to do it in 5 days. At least 3 times more better to ask time
Okay thanks got it
Btw, great idea.
Main account for any github/gitlab/banks to use STRICTLY WITHOUT plugins at all 😉
Chrome gives feature to have multiple users.
To use UBlock Origin (and optionally other plugins) for youtube and e.t.c. in a separate special user for watching stuff 😉
I think i can get used to it. I already did it for ticktock anyway
which front end framework would you recommend to use with django as back end and how do the two interact with each other ?
there is a choice only between three frameworks in my opinion
React, Vue.js and Angular
if you are ready to jump to TypeScript and wishing Google ecosystem, with hard learning curve: Choose Angular
if you are ready for Facebook ecosystem, the most popular frontend framework in the world, starting from just Javascript, choose React
if you are wishing the most simple to learn frontend framework, with ecosystem more or less rich as Angular, but not afraid that it came from China. Choose Vue.js
I tried Vue.js so far 
I would not mind trying React in the future
And at the same time keep in mind that scaling code is a bit difficult thing to do. If you are in Vue.js, make sure your project is relatively small. Or otherwise you could out grow your State management system
for bigger in code projects perhaps React or Angular could make a better choice
Vue.js is nice and simple choice for small projects
So all of these are usable with django without an issue ?
Sorry if this is a dumb question
but the way we are being taught is basically, they give us computers and a project and tell us : Do it, you have 6 months
any frontend framework is usable with django without an issue
wait a second, are you student?
so it is not for serious production?
yes basically but it is actually a serious production
erm. okay. Then React or Vue.js if it is intended for serious production. Angular is an option too, but I would exclude due to harder learning curve.
I think we'll use react then, seems straightforward enough for our current level
https://roadmap.sh/react this roadmap could be of help
i would look first at getting Router and State management
And thinking, do I need Internationalization tool?
Oh, and how to have Unit Testing
Since i am newbie to it, I would have checked those tools that make initial setup to add all tools for me (Create React App?
)
of course I could not live without SCSS, CSS without SCSS is plainly horrible
I would learn as first thing, how to DRY/split/reuse my code into smaller components of course
Due to me being a book person, I would be tempted to get a book 
I was asked to do insane at my level too. Time flew and I adapted to actually finish the project
people adapt to meet the requirements.
As long as they are interested to meet them
I was interested, because learning all this stuff was super beneficial to my career
django
request.user.student = None
request.user.save()
I have a Student model with o2o nullable field to user, but it doesn't detach with the above code, why?
i have these choices in my model field
choices = (
("Fixed", "Fixed"),
("Open", "Open"),
("InProgress", "InProgress"),
)
status = models.CharField(max_length = 20, choices = choices, null = True, blank=True, default='Open')
Hi
<td><select id="ab" data-item = {{vulnerability.id}} qty-item="{{vulnerability.status}}" class="update" onchange="if (this.selectedIndex) doSomething();">
{% if vulnerability.status == 'Open' %}
<option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option>
<option value="InProgress">InProgress</option>
<option value="Fixed">Fixed</option>
</select>
{% elif vulnerability.status == 'InProgress' %}
<option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option>
<option value="Open">Open</option>
<option value="Fixed">Fixed</option>
</select>
{% else %}
<option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option>
<option value="InProgress">InProgress</option>
<option value="Open">Open</option>
</select>
{% endif %}
how do make a dropdown on the user interface to show the current selected choice and also the other 2 choices to change it?
I have done this till now, is there a better approach?
Hi, Im using flask. I want to accept JSON and files in one HTTP request with mutlipart/form-data.
Please help
hi
Hi
im posting it with requests library and receive with flask.request
two python apps
so an API?
ok what do u want
from user to site to api
r = requests.post(API_URL + route, data=data, files=files, headers = {'Content-type': 'multipart/form-data'})
I have this
data is a dict
json
files is a dict of the file upload
so { filename : file }
theres 2 in it
it works fine i think
is it working?
the issue is data
heres the problem
on the API side when receiving
if I use
request.get_data()
it says
maybe try request.data, and print it to see what happens
same as get_data but
json.loads(get_data()) returns: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 1108: invalid start byte
well request.get_data()
and
request.get_data() without json.loads gives this error:
TypeError: byte indices must be integers or slices, not str
when I try to access an item in the json
with data["item"[
]*
when I do
data = request.get_data()
print(data)
its a massive byte array
OH
I see
my json is there at the top
after the json its the file data as bytes
i thought flask seperated that
the problem here is request.files is in request.data after my specified data
how can i get around this
request.data.data
any anyone help me with this?
n_json = request.data.data
AttributeError: 'bytes' object has no attribute 'data'
first try to decode it
hmm, youre right
decode(request.data, "utf-8")
Then to str
Right, the problem with decoding
same problem as get_json
it decodes as utf8
invalid bytes
on the file data
its not a string
its filestroage
not json
darkrex
im going to try this https://stackoverflow.com/questions/47679227/using-python-to-send-json-and-files-to-flask
its not pretty though
@delicate ore hello
my_data = {
'json_data': ('json_data', json.dumps(my_json), 'application/json'),
'photo1': ('photo1', photo1.stream(), 'application/octet'),
'photo2': ('photo2', photo1.stream(), 'application/octet'),
}
or the exact same without .stream()
photo1 and photo2 are the user uploaded files from flask request of type FileStorage
req_json = request.files.get("json_data") server side
with stream() TypeError: 'SpooledTemporaryFile' object is not callable
Hello
I got kinda off topic
BUt I'll be really GRaTefull if someone helps me by answering
without stream() TypeError: 'FileStorage' object is not subscriptable
these are some shits I found on my school websites <head><style type = text/css>
like these are some random fake porn sites and vpn ads
what are they doin here?
That's how the officials are taking care of money from your taxes 🤷
I am using the exact font and colors they give, yet my fonts look nothing like theirs
why
How do I only connect to a io socket once? Everytime i reload the page, it just adds another event listener instead of replacing the existing one
try to change the font weight
I did
Hello, I am currently working on an API using Flask, flask-resplus, Werkzeug, and a couple other less relevant packages. So flask-restplus is a little outdated and the newest version of Werkzeug breaks it: https://github.com/noirbizarre/flask-restplus/issues/777 so I downgrade it to what it should be, 0.16.0 or something like that right. And now the program gets broken again because Flask wants the current version of werkzeug: https://github.com/pallets/werkzeug/issues/2324. What is the work around for this? I've never had dependent dependency issues such as this one lol
what python libraries are a must for a python web developer
I think you should be asking more about functionality vs. which specific libraries. Lots of libraries do similar stuff
well what i am trying to ask is what does one expect a python web developer should know
django, flask, fastapi are the big 3 web frameworks
django is a jumbo-framework. It has pretty much everything.
flask is slimmed down without as many features, but still useable.
fastapi is the minimal required for making a REST api, but also supports other features if additional libraries are installed. Templates are supported if jinja2 is installed. Static files can be used if aiofile is installed. etc
flask uses werkzeug, while fastapi uses starlette as a wsgi/asgi implementation
Can anyone help me out? I have no idea if this is the right place..
Thanks! Ill look into it now.
I think FASTApi is exactly what I need. Much appreciated.
I checked out the help channels, but I don't have a problem with code, rather just questions.
ask your question
Yeah, this isn't the right place but ok
How do I start learing? Python..
Damnit I'm going to get banned for this
Yoo
Can someone help me real quick
My images wouldnt show up on the website
Im assuming it has to do with the path?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thanks
How to debug things in the browser: Open the page and press Ctrl+Shift+I to open the inspector. Click the console tab and look for errors. If none are found, go to the network tab and refresh. Look for any 4xx status codes.
You can press Win+Shift+S to take a screenshot
U want a better picture?
Did you refresh?
No
