#web-development
2 messages ยท Page 159 of 1
I honestly wouldn't have recommended trying to build an ecomm site if this is one of your first few projects. However... Given the situation I would recommend Heroku or PythonAnywhere.
As you don't want to have a security breach on the server.
dont worry , im not beginner in django
and not my first proj
so u mean
But you haven't deployed before?
pythonanywhere or heroku are the best choice
I did deployed on pythonanywhere
but when i tried to use 1i8n
pythonanywhere doesnt translate
though it does in local host
For this project, absolutely. If you haven't deployed before on your own server then go with a provided solution
is it babel?
noo its from django gettext
is your application translated when you are launching it with Gunicorn on your local machine?
Maybe try contacting their support, that or try heroku
Hello guys. I am working with flask in virtual env and i have installed this package with pip https://pypi.org/project/python-keycloak/. But the problem the from is not working
There is the error could not resolve in vs code
Someone have an idea why?
hard to say without seeing error
did you try to read the error?
well, wrong import name
keycloak is not installed, or you have wrong name used in import
or, you don't have activated virtual env for your visual studio code
heroku is 25$ price but i will try heroku
virtualenv is activeted i can see in the cmd and the flask is working
it does not mean it is activated for VS code
check at its bottom
which one venv is activated
Anyone here using Flask 2.0?
Im getting an issue after my upgrade from 0.12.5 where multiple api calls are not returning propery state from the endpoints. Rolling back corrects the issue so I'm not clear what changed in terms of controller responses within Flask
I haven't personally, but here's a nice article I've read through on it: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react
Cool
oh btw when i change from Sqlite to Prostegrsl , will it improve performance or it doesnt matter
we are using it at work
apperently it is actually quite common usage
Django in DRF mode is preferable
yea DRF is so great
i believe its better than pure html and css with django right ?
How is post request different from put request? I know post request would be like creating something new and then put would be updating/editing. We probably cant do put on something that doesnt already exist because there's nothing to update, unless the library falls back on post.
If I am using API to update an attribute called quantity for an item, would it matter if I use post or put and rest of the info about an item would stay the same? This is actually the actual question lol.
You can use DRF with javascript fetches from itself
For a simple javascript logic it can work fast and well enough
There are some alternatives if regular js is not enough
Basically... you can use appropriate mixes of regular pages / jinja / dynamic javascript stuff, in any proportions.
React just makes simpler handling a lot of js
nah i reactjs is better than regular js
agreed
Django isn't so good with templates so it really needs a frontend framework like React or Vue but i will go with react cause i Love it
I plan one day to learn react too
Too big queue of backend+devops stuff at the moment
I learned vue after react , Vue is very easy but react has a lot of features than vue
What to study after learning Js and Dom(js)
what do u want to do
there are numerous things to do using Js
UwU thanks
Also learn Django rest Framework
oh what is it used for?
ah ok thanks
let me recommend u some videos I watched
helped me alot
both are good , u can choose one
or both
then there's django + react
that's it
Tim is the best
thanks ๐ฏ freecodecamp is also good ๐
Absolutely , whatever u are comfortable with
bump
Yes it does matter. You need to use the verb that the api requires for that route.
Actually, I went through my code and realized I had used put to change the specific data because I know where the resources lives.
so what would happen if I had used post instead?
If I know where the resource lives, can I still use post?
@naive rock If the route accepts post then you should send it post. If you did put, you would get an error like 400/405
The same applies to other types
Hi guys, I came upon this kind of login page:
I notice no data is sent in the request body
How does the server receive this data?
Server: Apache/2.4.25 (FreeBSD) OpenSSL/1.0.1s-freebsd PHP/5.6.30
If it helps
what's the website? why is it hidden here?
@modest hazel have you checked the headers?
Cuz it's a little embarrasssing
It's a porn website lmfao
Yup
hmmm
i got it now tho, it's just base64 encoded, separated by a :
i need help with django auth signup form customization:
{% csrf_token %}
<div class="textbox">
<input type="input" class="form-control" name="username" id="inputEmail" placeholder="Username" name="" value="" required>
</div>
<div class="password">
<input type="password" class="form-control" name="password" id="inputPass" placeholder="Password" name="" value="" id="password" required>
</div>
<div class="confirm_password">
<input type="password" class="form-control" name="password" id="" placeholder="Confirm Password" name="" value="" required>
</div>
<input class="btn" type="submit" style="opacity: 1 !important;" value="Sign Up">
</form>```
does anyone know what's the id=" " of input Confirm Password:?
why isn't the action attribute an empty string?
?is it not
i mean this type of custom worked for my django auth login form
i've just copy-pasted that code here, but added the confim_pass textbox
/input
can someone help me with flask? Im getting an attribute error: AttributeError: 'Token' object has no attribute 'test' when i do return render_template("users.html", rows=rows) where rows is directly from a sqlite database
if im right its saying that your Token model has no field(attr) named 'test'.
yeah but i never interact with any kind of Token object @nimble epoch
or at least not directly
it looks like it's in my virtual env venv\lib\site-packages\jinja2\parser.py
Can you expand on the property state you're referring to and what info you're hoping to get from it?
The ID of that field can be anything. What are you hoping to achieve with setting that ID?
well
i belive it should be a unique id thats already defined within django.contrib.auth library
Hey guys. Does anyone have advice with learning Django? any youtube videos you can recommend?
how about to share your code in here? if you comfortable with it
dont you like main docs?
TIME_ZONE = "Asia/Kolkata"
why even after setting this in django settings I m still getting timezone.now() as 24 as the date?
its 25/5 as you will be able to see at the bottom right , but if you see the debugger variables then you will see it's 24
from django.utils import timezone
timezone.now()
datetime.datetime(2021, 5, 24, 19, 31, 23, 611639, tzinfo=<UTC>)
why?????
@ds12 state meaning the API responses.
I think it has something to do with how the flask server teardown the request
guys any idea how can I delete a user and the related posts data from the database?
form = DeleteAccount()
if form.validate_on_submit():
user = current_user
posts = Post.query.filter(Post.user_id==current_user.id).all()
if user.check_password(form.password.data):
db.session.delete(posts)
db.session.commit(user)
flash('Your account has been deleted.')
return redirect(url_for('logout'))
return render_template('delete_account.html', title='Delete Account', form=form)```
ye forgot to mention the framework==flask , so this is my delete account func and it throws me -> sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped
you use sqlalchemy right? you can use id to delete all his/her posts but you should use cascade
dont look at this point -> db.session.commit(user) mistake
ye
and this view is for deleting user and its posts?
yeah
and i dont know it's your app or not but you dont need any forms to delete user
just a button
yeah its actually a link but yeah you can do it with js button onclick attr too
this is how it looks like
oh so it need password to delete user so its ok
yeah
so just add cascade="delete" on my users relationship?
i dont remeber well sqlalchemy but yeah i think that was something like that cascade="delete delete-orphan" or something
@nimble epoch What is main docs ๐ฆ
idk still nothing, and I am getting the same error :/ but thanks for your time
django official documents
what was the error? and doesnt sqlalchemy need any migrations?
sqlalchemy.orm.exc.UnmappedInstanceError
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped
db.session.delete(posts)
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), index=True, unique=True, nullable=False)
email = db.Column(db.String(64), index=True, unique=True, nullable=False)
hashed_password = db.Column(db.String(32), index=True, nullable=False)
joined_time = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
user_post = db.relationship('Post', backref='user', cascade='all, delete, delete-orphan', lazy=True)
def check_password(self, password):
return check_password_hash(self.hashed_password, password)
def hash_password(self, password):
self.hashed_password = generate_password_hash(password)
def __repr__(self):
return 'User {}\nusername:_{}\nemail:_{}'.format(self.id, self.username, self.email)
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), index=True, nullable=False)
date_posted = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
text = db.Column(db.Text, index=True, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='cascade'), nullable=False)
def __repr__(self):
return 'Post {}\n{}\n{}'.format(self.id, self.title, self.date_posted)```
i remember something like that but im not sure whats the solution
doesnt it mean that the record you looking for doesnt exist?
honestly idk, it is already created, but I am going to google it I guess
ye better
When you are adding a non-model-object into the session, you will be getting UnmappedInstanceError. so the solution was to remove the -> db.session.delete(posts) | posts = Post.query.filter(Post.user_id==current_user.id).all() , and it deleted succesfully the user and the related posts to it
I only needed to delete the user after I added cascade to my model
but still wondering why ๐
nope
i think thats because of that BUT this can happen when you have added new field to model and already had a record but that field in the record is empty
Hey guys just wanted to ask something. Two people including me are working on a django project and both of us have no big experience with github. Whenever we push our codes, mine work fine, but his push generally creates some kind anomaly or what, making the whole branch corrupt. Would putting migrations files into .gitignore a good way or shall I search for something else??
Please tag me if you answer this
I think think not staging the migrations is not the best idea... are u both working on the same branch?
Yes sort of
I mean i do have my separate branch which works fine with my code
But the problem is when we work on the same branch
what kind of anomaly do u have, can u be more specific
I think it's kind of " <<<<<head " appears in code in many different places
in the code or specifically in the migrations
if so a possible solution could be a solution for you https://stackoverflow.com/a/32683732/12232281
I hope that this will work for u and your team m8
if not i would suggest that u research a bit there are many other people that have the same problems and established a work flow for them self
is there a good tutorial for Django?
have u tried the offical?
https://docs.djangoproject.com/en/3.2/intro/tutorial01/ it's a nice introduction
oh cool thanks
no problem and good luck
just update the current working directory before you both start working on your code.
from simple_websocket_server import WebSocketServer, WebSocket
#Basic server for receiving data from webclient
class basicServer(WebSocket):
def handle(self):
global messages, returnMessages, count
print("GOT NEW MSG",self.data[0:10])
messages.append(self.data)
while len(returnMessages) > count:
self.send_message(returnMessages[count])
count+=1
def connected(self):
global running
print(self.address, 'connected')
def handle_close(self):
print(self.address, 'closed')
server = WebSocketServer('', 80, basicServer)
z = threading.Thread(target=server.serve_forever)
z.start()โโ
https://github.com/pikhovkin/simple-websocket-server/blob/master/simple_websocket_server/__init__.py
source ^
How can I use send_message outside of basicServer class
Anyone here know how to import a js library from cdn to use in a js script.
You can use a <script src="cdn url"> tag I believe
Ah, my bad
I got this error as I was trying to build a simple web app
that will display informational graphic
Can anyone provide me with a basic understanding of what Flask does?
Set of libraries
Gathered neatly together
Which solve all your basic problems on the path of making web site
Flask solves for you requests, routes, gives... template language, makes possible easily handling basic operations like login, or any other data insert, web site auto translation(also known as localization), gives basic web server to try running it, handling database connections and migrations and etc
Basically, do not reinvent a wheel, when people already all made for you
Can anyone help
Just google the full RunTimeError exception message. There seems to be a few threads with potential solutions you can explore.
Already have..nothin worked..ty though -sigh-
@quick juniper @opaque rivet Thank you
I'm working on a blog platform in Flask. I'm trying to simplify the permissions/access for posts that users can create. Every post's access is controlled by two variables: is_published (a bool) and visibility (a enum).
Basically, for every endpoint, I don't want to have to micromanage which user has access to being able to see the post. Is there a design pattern I should use to deal with this, or some kind of library?
Can you clarify on what you mean by micromanage which user can see a post? Given what you said, a post that isn't published doesn't get shown (obviously) whereas the visibility piece determines which types of user can see a post?
How do I make div blocks over and over again in jinja2
Unpublished posts are only visible to the author.
Visibility levels including things like, whether it's visible just to friends, the public, is unlisted, etc.
Users can customize visibility levels (and unpublish posts)
Right now the way my project is, I have to manage the permissions in every context/endpoint, and this logic the spread out.
Eg, if you want to access a list of all posts in have to customize the query to not show unlisted and unpublished, but if you're the author you should be able to see all of your posts. When you want to edit the post, there's logic there to make sure you're not editing other people's posts. Just seems like I can simplify all of this logic in one place.
I should mention in doing everything server-side. Nonfront end frameworks or anything.
How to deploy django with celery
Can you share some snippets to how you're managing these permissions?
Why you want permissions snippets
Talking to @native tide
Can you give my question answer please
Okay, I'll have to do this tomorrow.
you should definitely look for a ready made library or build one for your case
usually you will require 2 things. 1 - check if user has permissions for a single object, 2 - filter the list based on permissions
if you design your schema properly then neither becomes a pain. You can write helper methods somewhere in lib, may be a decorator and just use that
you should also explore "guard clause" design pattern so that your logic can be simplified
they have a full guide on this. Have you tried that? https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html
Yes... I mean it is possible to deploy django with celery
If yes please guide me
what have you tried so far? what is not working?
No I don't tried yet i.am asking dod you done something like this earlier is yes please tell
yes. I'm running celery in production for few years now. It's the exact guide we follow
there are more than handful things to take care of while deploying celery with django. that's why I'm suggesting you to go through that guide and try to setup things. If it doesn't work then we'll help
otherwise helping you do that will be another exercise to write the same guide here
to sum up celery deployment, 1. make sure you have django server running on gunicorn/nginx etc 2. make sure redis/rabbitmq is running and configured correctly 3. run celery worker 4. if you have periodic tasks then use django-celery-beat 5. profit
hmm, thinking what are the advantages to pack postgres into container
Oh
how can I center something in the middle of the screen, but allow it to be reactive (Things will not overlap).
.wrapper{
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
I want the items to site around the search-bar
it will help in putting everything in a same virtual network, easy deployment using docker-compose or so but you will lose data if container is destroyed. Then you have to make sure to use volumes (external ones, mounted on the container) to persist the data. I'd do it only if I had orchestration benefits, otherwise no
mm yeah. like... I don't need my each app having its own instance of postgres
it would be great... but they need to be 'mirror'ed to each other in this case in order to share the same data
but it can't be resolved at this level
I know this is a python discord but are CSS questions allowed in here?
I can't figure out why multi-lined text in my pseudo table are not being justified
.search-input{
margin: auto;
width: 60%;
border: 5px solid #FFFF00;
padding: 10px;
}
how can I make it so that the orange thing goes away, I want the stuff below to flow nexzt to it
huh?
hm
I wanna make it so there is a searchbar and there are elements around the outise
closest i
have got
can you make a rough sketch of what you want it to look like?
https://cdn.discordapp.com/attachments/366673702533988363/846658688613613588/Screen_Shot_2021-05-25_at_5.59.04_pm.png
like that without the overlap
the elements on the side
but like when I position it, the elements don't go around it
it creates a margin
even if I set margin to none
no, i mean the position property
you mean position; relative:?
you can change it's z index to bring it ontop of the other elements
that could work, but i think fixed works better, just mess with top, bottom, left and right property to center it
I tried that
it sets a margin around the outside
therefore the items will not sit around the outside
I need the div to stay as the yellow dimensions
instead thats what it looks like
so you want
the search bar to be in the middle?
I mean yes
man, i dont understand what you want
yeah I don't either
hmm
can you
I want the searchbar in the middle, and the other items to float around it
I see what you're trying to achieve, but I think to make it nicer for users I'd just make the search bar span 100% at the top instead of embedding it between search results.
draw EXACTLY what you want
okay
then it needs to be in the same container
as the results
that sounds...weird...though
IMO
wtf
hm
thats not an exact design
result result result result result
result SEARCHBAR GOES HERE result
result result result result result
or
more like ```
result SEARCHBAR GOES HERE result
result SEARCHBAR GOES HERE result
result result result result result
result result result result result
result | | result
result | | result
result | SEARCH GOES HERE | result
result | | result
result | | result
then
that is simpler
use flexbox
with 3 columns
middle column contains search
done
ok lemme try
If I can just give my opinion on this, I recommend sticking to the layout below, it's more accessible and has better visual hierarchy:
<search result> <search result> <search result>```
its gon look clean asf in the end dw
agree
I doubt it
its gon be a unique design
it also seems to have accessibility issues
ill ping u when I do it
no need to ping me
E.g. FontAwesome is a good example of a nicely structured search.
kk
I have done enough UI/UX design to see
lots of people
who think their design is new and unique
indeed it is
xd
but most of the time
it also fails miserably in the usability department
new and unique is easy
new and unique and PRETTY is not difficult
new and unique and pretty AND usable is hard.
but I'm sure you've done your user interviews and gathered your focus groups
and thereby validated your design
@marble spade One more thing, your design doesn't look it it will be responsive, especially on mobile.
You'd have to start moving things around and most likely get rid of the 3 columns on mobile anyway...
If there's something I retained on frontend/UI/UX is that you have to keep it as simple as you can
I say this while I barely know how frontend works and my speciality is changing font sizes, weights and colors
The first thing I learned it to keep the basic rules in mind like visual hierarchy, scale, use of whitespace, etc. As long as you have that you can expand on it and create your own unique design.
hi, I want to display my image as url as follows
127.0.0.1:8000/media/images/product123.jpeg
How, can I do this?
I am storing my image as follows
image = models.ImageField(upload_to="images")
i have those models, I am trying to make an api call that returns something like:
{
class_a:
{
firstname: john,
lastname: do,
total_score: 200,
},
{
firstname: jane,
lastname: do,
total_score: 300,
}
class_b:
{
lastname: steve,
},
something like that. somebody help
Btw is there a way to deploy a dockerized service without using swarm or Kubernetes?
I have something working with docker-compose
its right. doesnt it work?
make sure you adding static to urls
No, I haven't added.
Can you please tell me what I have to add?
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
add it in your app urls.py
use this code in DEBUG mode
you can do something like ```py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have added this then it creates another error.
what error?
When I am writing debug =false it is not working.
So, how can this work with debug =false
I am using this as well.
not working?
Not working
you added whitenoise to middleware and storage attr to settings right?
Yes
do static files work? i mean static files not media files
and did you do a migration?
whitenoise middleware should be under securitymiddleware
yep
But still I am getting this๐ญ
do another migration of course if its necessary then try it
What do you mean, didn't get you..
what are you using? flask?
No , django
How to add a simple messaging feature to my django website using websockets ?
i think your issue can be solved with dynamic routing
My theme is not to make a chat app but I wanna add a feature in it
Use django-channels
What is this, and how can I do this...
Will that take time to implement bro?
Yeah, it will take sometime to learn.
okay let me look into it and thankyou
i'm not sure how to do this in django but in flask you would have something like this
@app.route("/media/images/<filename>")
def getImage(filename):
#here would be some function to return an image based on the filename
I am not familiar with flask ...
I know this name only.. nothing more than this
maybe this will be helpful
again i'm not familiar with django
so i'm just taking a leap and guessing here
This won't solve my problem.
ok then
i know im trying to fin out
ok, can you explain how dynamic urls dont solve this problem for you?
ill let you know
Thanks
I never say this won't solve my problem, I say I am not aware of it, can you please tell me what is this...
you get the filename from the dynamic url, you use the filename to find and serve the image
ultimately you want something like this right?
let me ask you this, if you had the filename for the image, could you serve it?
I have filename but I am not able to serve it.
In production mode.
I am able to serve it in debug mode.
Hmm
if you don't want your website being discovered
is it safe to attach it to 80, 443
or better hide to some other port
Hide to some other port
Which one is the better option?
- PUT /message/{message_nr}
- payload
{
"text": "string",
}
- PUT /message
- payload
{
"text": "string",
"nr": 0
}
I would use the first since I use PUT for updating/patching.
both are PUT
I know
But to pass it through the url, since itโs identifying a resource
And benefits of that is also some frameworks can auto resolve it for you through dependency injection.
hi, I am having a problem
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/hi")
def rudransh():
return "Hello rudransh!"
if __name__ =="__main__":
app.run(debug=True)
when i run the code and change the end point to /hi
it shows error 404
Anybody knows how to set a docker-compose so the proxy/front is exposed on one particular host and port?
Did you launch python app.pyor whatever your file is called?
hey guys, Does anyone know how to use adafruit feeds on django?
i mean i just ran my code
Do you have an error message when you launch it?
no
Because a correct launch means your terminal is runnung your Flask app and you can access it at http://localhost:5000
Nevermind, I saw that and you need to stop Flask and restart it for the changes to take effect.
* Serving Flask app "FLASK WEB APP" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 311-665-859
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
it shows 404 error when i change the endpoint
Yeah your app is running. If you go to http://localhost:5000/hi you should have ยซย Hi rudranshย ยป showing up
that's not showing
But if you added more routes in the meantime, you have to stop with Ctrl+C and restart your app
it's showing a error instead
Oh
Yeah 404 means the route doesnโt exist. Meaning you added it after you launched your app for the first time
yeah
If you want /hi to be shown, you have to stop your Flask app and restart it (also donโt forget to save)
Refresh your browser
If nothing works, clear the cache and restart your FLask app
Or open your route in a private tab
Iโm sure you probably forgot one of the steps Iโve indicated
Anyone know why vs code might not let me connect to the server via any browser sometimes but then if I just restart my pc it works? It seems to be happening like 50% of the time that I can't connect.
Also never name your Python files like you did. Python files must be named with snake_case.py
The other recommendation I can offer is to start over with a virtual environment with Flask 2.x installed and follow the quickstart tutorial just one more time
Lpl
Just take it one step at a time bro. Debugging is always going to be an issue. No point in getting frustrated. Just take a breather, get some air or some coffee and take another look or start from the beginning. ๐
Btw I wanted to know if there were any webdevs who successfully deployed a dockerized app on a VM with a fixed IP and a fixed port. How do you bind your app (the front-end network) on that fixed host + port, through docker-compose ?
backend just has exposed ports
which front end uses (preferably its pointed by env parameters)
shrugs, I do separate docker-composes for separate code projects
I only make multi conterized dependencies for the same project only for
backend app + redis + postgres + nginx + celery
Yeah, my goal was to expose the frontend's ports while the backend communicates with the frontend on a private network
My docker-compose.yml files englobe the whole project. Never tried to override them in case it gets too complex
well, there is expose flag which exposes port of container for internal private network inside of docker-compose
Ok I tried something on the port param:
ERROR: for web Cannot start service web: driver failed programming external connectivity on endpoint react-frontend (CONTAINER_ID): Error starting userland proxy: listen tcp4 XX.XXX.XXX.XX:YYYY: bind: cannot assign requested address
Where XX.XXX.XXX.XX:YYYY is the address I want to bind my container on
Yeah the XX is an IPv4 while YYYY is the port number
bind to 0.0.0.0: YYYY
it makes application exposed to the network outside, while taking exernal IP as its
Ok. I'll try the universal IP and see what gives
Man, next time I'll try Swarm or Kubernetes
just install nginx on the server and reverse proxy it to docker container port
Yeah the frontend is running through a NGINX image
Because I set up a Dockerfile for production ready to use
it will take additional efforts to bridge the networks, no?
your docker-compose net will have it's own subnet and stuff. then your nginx image will require to co-ordinate between external world and docker's internal network
and the nginx within container will never see your host machine's network adapter, hence it won't be able to bind to that ip address
what is the host os on your vps server?
Oof it doesn't work. The address sends back a 404 response
It's a static IP. Also the advantage of Docker is customizing the entrypoints isn't it?
static ip or not, that's not really very useful in this case
Print ("hello")
404? it found your web site at least? perhaps just wrong page url
could you please share your docker-compose?
On my local machine, it works fine.
Here:
version: '3'
services:
api:
restart: always
build: ./api
env_file: ./api/.env
expose:
- 8000
ports:
- 8000:8000
volumes:
- ./api:/api
container_name: fastapi-backend
restart: always
networks:
- api-front
web:
build:
context: ./web
dockerfile: ./Dockerfile.prod
args:
environment: prod
status: stable
expose:
- 80
- 443
ports:
- 0.0.0.0:4000:80
- 0.0.0.0:4001:443
container_name: react-frontend
volumes:
- ./web:/web
networks:
- api-front
networks:
api-front:
I'm gonna try locally
ports are mapped as host:container, this means your web container internally has something running on 80 and 443 that you are binding to 4000 and 4001, is that correct?
also, you should not set container names in the docker files. containers should be stateless and if you somehow want to recreate the containers then names will clash and compose start will fail
can we see docker file of your front
at least its ending / entry point / cmd
Here:
# Build env
FROM node:16.0.0-buster-slim AS build
WORKDIR /web
ENV PATH /web/node_modules/.bin$PATH
COPY package.json ./
COPY package-lock.json ./
RUN npm ci --silent
RUN npm install react-scripts@4.0.3 -g --silent
COPY . ./
RUN npm run build
# production environment
FROM nginx:stable-alpine
COPY --from=build /web/build /usr/share/nginx/html
# If you have a nginx.conf file, copy it
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
nginx conf?
Yeah
fix ports for web like this
ports:
- 0.0.0.0:80:4000
- 0.0.0.0:443:4001
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
@inland oak
hmm
also, is your react-frontend expecting to connect to fast-api server on localhost:8000 ?
Yeah
version: '3'
services:
api:
restart: always
build: ./api
env_file: ./api/.env
expose:
- 8000
volumes:
- ./api:/api
container_name: fastapi-backend
restart: always
networks:
- api-front
web:
build:
context: ./web
dockerfile: ./Dockerfile.prod
args:
environment: prod
status: stable
ports:
- 0.0.0.0:80:80
container_name: react-frontend
volumes:
- ./web:/web
networks:
- api-front
networks:
api-front:
technically it is supposed to be something like that
if we will remove all not working ports
0.0.0.0:4000:80 as alternative, if you don't want being published at 80 port
react-frontend won't find the fastapi server because react-frontend will try to connect "within itself" when pointed to localhost. For this connectivity you need to specify fastapi host as "api" <- this is the key you have define in docker compose as service name. Docker's dns server will help resolve the correct ip on it's internal network
there are 2 networks here. one is "api-front" that docker manages. and your "web" should be able to locate "api" on this network. Second is the actual network of host that connects it to the internet. That one you'll be binding on using ports directive under "web"
Yeah I need to make API calls from my React app
you need to change hardcoded hostname from web source code. Change it from "localhost:8000" to "api:8000"
and change the way you have mapped ports on web, as I have suggested above and give it a try
I just referred to some of my old deployment files
ports are mapped host:container
Really? Do I have to use the service's name?
Hold on, that means I have to edit the middleware too
I've got a request that if a condition is true, it'll re-try in the backend in ~30 minutes after, for the response to the client explaining that this is going to happen, should I use status code 202 for accepted or status code 425 for too early?
make it configurable from env vars
take a step back and understand how docker's private network works and what localhost means for a container. It means itself! Once you understand this part, docker-compose and networking will be very handy!
Time to take networking classes ๐
if you are actually acknowledging the incoming request and pushing it to some sort of queue then 202 makes sense. If not then 425. Depending on this status code client will define their behavior, right? if you have ack'ed but reply with 425 then client will keep retrying may be every 5 minutes to get it in. If you were not ack'ing the request but responded with 202 then client would be under the impression that it doesn't have to do anything and just wait for it to complete.
it's not that hard
yeah its sent to a queue
but thank you
ill use 202
Did you manage to debug it in the end?
I want the output(string) of my python code to become a headline in a HTML file
any help?
<a href="/create">Create</a>
``` urls.py ```py
path('create/',views.create,name='create')
``` its not working anyone know how to fix this?
store the output string in a variable and use {{variable}} in html (idk this work or not )
Can anyone tell me why I am getting this, when I am doing debug =false it is giving 404 error and when debug=true it is giving 200 code .
Okay i will try
doesnt work...i need a way to connect html and python
because django does not serve static files in production
using django?
So I have a site that saves whatever is uploaded to the site. How to get the web app (using python and django) to just print the JSON file uploaded? End goal is to eventually allow user to pick any graph they wish their JSON file to be represented in , and show the statistics that way
You can use flask and render_template(<html file>, <the output>)
And in the html file use {{the output}}
Thanks will look into it.
i think you gotta use django-storages and whitenoise cant handle media files it only handles static files
I am not using django-storages, yeah, I also understand this that media file is not showing in production because of whitenoise, after creating a different project and doing all the things except whitenoise, but the problem is that I have to use whitenoise because I am deploying it into heroku.
no difference use whitenoise beside django-storages to serve you media files
Whitenoise is creating a different folder for static files as staticfiles, means it has not to take anything from static folder , may be it is also ignoring media folder, I am not sure.
is django and react a good combination?
they are great
hi all.. i have an issue about django, can anyone help?
can i leave a stackoverflow link here?
anyone?
whats wrong?
yes you can
hey, can anybody recommend some js courses which are good
im new so cant figure out why pinax implementation isnt working, in summary i used {% url 'django urls -for a signup button, but when i click it it redirects me to the index page. migrations are all working. it seemslike im missing something really basic but i cant see it since morning.
What's the key difference in using management command and runscript in django?
IS it login_redirect_url setting?
How do I take a JSON file that has user data and convert it into graph data in my python django web app?
So far I managed to get two graphs showing on web page with generic info. However, I wish to have it where one can upload a JSON file of random user data to be displayed in a graphical form of one's choosing(pie char, bar, etc)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Please Upload File Here</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<!---- Code used to have multiple graphs on one page -->
<canvas id="myChart1" style="width:100%;max-width:600px"></canvas>
<br/>
<canvas id="myChart2" style="width:100%;max-width:600px"></canvas>
<!---Chart 1--->
<body>
<script>
var xValues = ["Male", "Female"];
var yValues = [55, 49];
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
new Chart("myChart1", {
type: "pie",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues
}]
},
options: {
title: {
display: true,
text: "Test1"
}
}
});
</script>
</body>
<!----- Chart 2 --->
<body>
<script>
var xValues = ["Male", "Female"];
var yValues = [55, 49];
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
new Chart("myChart2", {
type: "pie",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues
}]
},
options: {
title: {
display: true,
text: "Test2"
}
}
});
</script>
</body>
<!---- end of chart 2-->
<body>
<form method= "POST" enctype = "multipart/form-data">
{% csrf_token %}
<input type = "file" name = "file">
<br>
<input type = "submit">
</form>
</body>
</html>```
I have managed to have button where you can upload any file and it is saved(I check admin side and see said uploaded files save so I got that going)
But no proper functionality to my web page
My goal is to essentially do this:
Making a single-page web app that displays informational graphics about the randomly generated users.
On the initial page load, the user should see a form that allows them to either paste the JSON into a text input field or upload it as a file.
Once the data has been entered, you should display the statistics in graphical form, using any charts, text, or interactive elements that you like.
Back End
Please expose a REST API endpoint that takes random user JSON data and a file format as input, and returns a file containing the statistics.
Supported file formats for the results should include JSON, plain text, and XML. For example, the plain text file returned by your API endpoint should
contain a line like, "Percentage female versus male: 66.6%".
For bonus points, instead of requiring the user to specify the file format, determine it automatically from the "Accept:" header in the HTTP request.
The specific format of the data or text your API returns is up to you, as are the details of the URLs you expose```
how does chart.js work?
nvm. bar graphs, plots and pie charts etc are normally produced with numerical data. sounds like what you need to do is basically use the random json data to produce numerical data that can be used to plot whatever it is you want
It does have calculations
I did percentages
On a python file I have
Of course the code currently is doing statistics /calculations based on the file I specified to open
But I do wanna have it tweaked where it can do it for any JSON file uploaded to page
Kinda likeโฆ putting puzzle pieces together
what kind of info do you want to convey with your graphs?
just do a count then?
I experienced big trouble from whitenoise. For some reason it served files with 4-8 seconds delay. Nginx is much better way, serving became nearly instantaneous.
Wonder if that's a good alternative to d3.
That's a good thing since I can't rely on matplotlib forever
Else I might be stuck with apps like streamlit
hello everyone i hope you're doing pretty fine so anyway i got some questions, im a newbie in webdev and im willing to become a full-stack web developer so im starting with the front-end (html,css) and i kinda grasp it a bit and in parallel i'm learning python and still in the basics(loops, functions and i will start in classes soon enough) and after that im thinking to study a bit of backend
note: i made two projects in python gui ( using tkinter i made a calculator and a tic-tac-toe) and now i wanna get my hands on the backend i still have some difficulties in the language itself "python" and im here to ask for your help, please :
- how can i improve myself in python to go from just the basic to a moderate or even advanced level in it, how to get out of tutorial hell basically and start making ideas happen and to kinda go from that obscure big idea to the small technical details you'll develop in python and also if there is a detailled tutorial that goes from babysteps to big outstanding advanced concepts
2)i find a difficulty of grasping the backend and a bit overwhelmed since i feel a bit inferior to where i should be if anyone knows a ressource a where i can learn the fundamentals and the basics of the backend using python - can i develop the backend using only vanilla python and without being tied up to framework ( i'm not planning to build apps in using only python ofc ill use a framework just out of curiosity and i might do that if im good at python)
no
building a backend from scratch is possible
but way too complicated for you right now
thereโs a lot of routing code which requires you to have a good low-level understanding of networking
itโs not trivial
would knowing a low-level language( C/C++) would help me understand these fundamentals in networking
yes
but I would not reco building your own backend
it doesnโt really train the right thing
because the whole point of a framework
is to abstract away the details of routing etc.
so you can focus on the business logic
it would be like trying to become a better racer by working as a mechanic
like sure you might learn some tangential optimisation techniques but that would likely also be a sign of a leaky abstraction
ohh i get it and what about sharpening my coding skills in python what do you recommend i just thought to start python all over again from the very beginining starting with this
I have an app with a home page, where there is a button named "Run", which when clicked will create an excel file that is stored in some location in the project folder. Now I want to give a download option to download that excel file. I tried with HTML attribute
<a href="path\_to\_file" download="file\_name.xlsx"></a>
Now this will download the file properly. But when I try to open the file in Ms-Excel it gives an error.
Cannot open the file, the file is corrupt or file format is not supported.
So I'm working on this blog engine in Flask, I have it all quite nicely as I want it including a fully functioning REST API.
Should I use a frontend framework? or just keep using server-side pages with Blueprints, Jinja templating, and all that? What's the decision process that goes into this?
I should note that I want this blog's viewing to be as absolutely lean and stripped-down basic as possible. I hate how frontend JavaScript's frameworks are so computationally intensive, but if there's one that is very simple I'd happily use that.
In my opinion, a framework would be easier because you can use pre-existing libs, e.g. material-ui
I'm already encountering complexity, having to code up a lot of crazy metaprogramming solutions to manage Jinja macros, blocks, extends...
Are JS Frameworks inherently laggy, or is it in how you code it?
how do you define variables in an html page ( jinja template)
How you code it and depends on the framework. Next.js should not be laggy at all for example
Oh there's also Elm! Forgot about this thing
It looks like Elm's development has been stagnation. That is unfortunate. It's been ranked as one of the fastest frontend frameworks.
how to use django.db.models.Q standalone
for ex. Q(name__icontains='test')
how i can get a string from above like "name like %test%"
i want to write raw query which will take condition using the Q object, so that i can use OR and AND
Is there any way to render two html files in flask?
like this
time.sleep(2)
return render_template('wassup.html')```
hey, is there any way to use requests_html to continuously execute a javascript command on a webpage then save the html to a file?
ive got it down to where it can save the original webpage, how it changes after the first command, but then after that it just saves it like its the 2nd page alone
from requests_html import HTMLSession
import os
session = HTMLSession()
resp = session.get('https://rgl.gg/Public/PlayerBanList.aspx?r=24')
a = 1
for x in range(170):
if not os.path.exists(f'./bans/{a}.html'):
print(f'Writing {a}.html to files')
f = open(f"./bans/{a}.html","w")
f.write(resp.html.html)
f.close()
resp.html.render(sleep=5,script="javascript:__doPostBack('ctl00$ContentPlaceHolder1$btnNext','')",reload=False)
else:
print(f'{a}.html already exists')
a += 1```
here is the relevant code
what is better for react? served with npm serve, or perhaps better would be nginx
I feel like, Nginx is trusty and more secure way to serve react
actually perhaps it is so
nginx ftw
there are more haproxy is also good
Btw @inland oak I tried your solution and I have this error ERROR: for web Cannot start service web: driver failed programming external connectivity on endpoint react-frontend (5f3e24bb667b521ad65ba2704315a42eac3ad1a2e83d888ac5e55affe5dd039b): Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use
when you return nothing after it gets executed also to do that maybe merge the html files
having happy debugging time
oh, I actually was able to solve it
not in the best way yet though
yup, I solved for sure now
there is in nginx 80 port busy by default
there is application running (basic nginx page)
COPY nginx/nginx.conf /etc/nginx/sites-available/default
RUN service nginx stop
CMD nginx -g 'daemon off;'
I replaced its default file with mine
service nginx stop shuts down the current NGINX service outside the container and keeps port 80 busy, right?
does 'rest_framework.authtoken' causes problem with simple jwt ?
nope
this is my students Model.py
class Student(models.Model):
name = models.CharField(max_length=20, blank=True, primary_key=True)
omang_id = models.CharField(max_length=20, blank=True)
email = models.EmailField(max_length=254, blank=True)
male = 'male'
female = 'female'
gender_CHOICES = [
(male, 'male'),
(female, 'female'),
]
gender = models.CharField(
max_length=7,
choices=gender_CHOICES,
default=None,
)
phonenumber = models.CharField(max_length=20, blank=True)
course1 = models.CharField(max_length=20, blank=True)
course2 = models.CharField(max_length=20, blank=True)
result1 = models.CharField(max_length=20, blank=True)
result2 = models.CharField(max_length=20, blank=True)
DateOfBirth = models.DateField(max_length=20, null=True)
New = 'NW'
Renewal = 'RL'
Purpose_CHOICES = [
(New, 'New'),
(Renewal, 'Renewal'),
]
Purpose = models.CharField(
max_length=2,
choices=Purpose_CHOICES,
default=New,
)
address = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
def __str__(self):
return self.name
this is the students profile views.py
@login_required()
def Profile(request):
UserProfile = Student.objects.all()
return render(request, 'W/Profile.html', {'UserProfile': UserProfile})
i would like to know how i can only show the currently logged in users information and not just everyones information
also im a newbie thus i do not understand how to override the queryset
when you login the user using django auth you can access your user and user data using request.user, request.user.username, ....
ether in views or templates
So...
I deleted my app from heroku, and I created a new one in the cli.
It says the app is created, but when I try to push, it is still trying to push the old one that got deleted and is therefore raising the error about how the old one does not exist.
How do I get it to look at the new one?
Hey hey just a quick question I'm using flask to create an API, i'm trying to get the client to send a .wav file to the server but I can't find much online to help me out
import requests
BASE="http://127.0.0.1:5000/"
with open('audio.wav','rb') as file:
files={"audio":file}
resp=requests.get(BASE+"SAVAVOICE",{"audio":files})
print(resp.json())```
This is my client side
class SAVAVOICE(Resource):
def post(self):
request.files['audio']
audio = speech.RecognitionAudio(request.form['audio'])
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code="en-US",
)
for result in response.results:
print("Transcript: {}".format(result.alternatives[0].transcript))
return ''```
And this is my server side
I'm trying to use the google speech to text API but I need to get the audio sent over first of all
Could anyone lend me a hand?
If nothing else, you'll need requests.post(BASE+"SAVAVOICE", files=files)
Then, on the server side, you'll probably want to do speech.RecognitionAudio(request.files['audio'].read())
Though, looking at the docs of the recognition API, it might need some changes.
speech.RecognitionAudio(content=request.files['audio'].read())
But I'm not sure about that part.
Hi, according to the django doc, I try to conf templates. I have APP_DIRS : True and I have templates folder in app directory, but it doesn't work. I also try to add path to templates folder to DIRS but still nothink. Were is my mistace?
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello_world():
return render_template('index.html')
@app.route("/about")
def my_name():
name = "rudransh"
return render_template('about.html', name=name)
@app.route("/bootstrap")
def bootstrap():
return render_template('bootstrap.html')
app.run(debug=True)```
this is my code, when i go to /bootstrap it shows error
I had suffered with this error before and had to start all over
we dont know what error you are receiving mate
I need HELP...I want a tree text file...I have some mp3's and folders in my e drive...each folder has mp3's and subfolders with more mp3's...there r other pdf and other format files as well...I want to create a text file which contains all the mp3's names in lists under album names with album numbers all sorted by hierarchy and order....for example...album1 would contain the names of all the mp3's in the home page of e drive...album2: names of all the mp3's in the 1st folder of e drive...album3 would be names of all mp3's in 1st subfolder of 1st folder...if 1st subfolder has no more sub folders, album 4 would be the names of all mp3 files in 2nd subfolder of 1st folder...if 1st folder has just 2 subfolders then move on to the next folder in e drive and so on...All other files lyk pdf,etc r to be ommited
404 error
๐ Can someone gud at parsing,and commands please help??
it has solved but when i run my 1st file it works and then when i run my 2nd file it doesn't work
yeah it hink
there's no bootstrap.html there
expand the folder
so when i run firstapp it works, but when i run wow it doesn't work
if this is the case, simply restart the server
but why this happens
do your files have the same code?
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello_world():
return render_template('index.html')
@app.route("/about")
def my_name():
name = "rudransh"
return render_template('about.html', name=name)
app.run(debug=True)```
code of first app
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello_world():
return render_template('index.html')
@app.route("/about")
def my_name():
name = "rudransh"
return render_template('about.html', name=name)
@app.route("/bootstrap")
def bootstrap():
return render_template('bootstrap.html')
app.run(debug=True)```
code of wow
ok what is the issue again?
firstapp code runs and I can see bootstrap.html page, but when i run wow.py it shows 404 error
what;s the problem I dk
how is the first app working when it has no bootstrap path?
So in my login model I should specify to request the user in relation to my username
Are you migrating from 'global' templates? If so, you'll still need to put the template in the templates folder in the app with the path you had it in the global one
I dont see global folder templates, I just create templates folder in my app dirc
ha?
Did you restart your runserver, I vaguely remember there being something weird with adding new folders
can some one teach me django rest framework authentication like basic session token??
Hey guys, how do I sell a single line from a text using django.
An example would be keys of a software. I paste many keys and it mails one of it on purchase.
sounds like ecommerce
don't know if this fits your needs but try this https://github.com/mirumee/saleor
yep.
thank you very much. will look into it.
Hello, I want to get simplest tracert in Scapy, maybe someone has one? mention me or dm me please if you got one
we can't help you, cause we can't see it
Please give us more details about it.
Anyone have any experience with getting Cloud Run to access a PostgreSQL DB in Cloud SQL?
On GCP?
should i simply type the html divs in a single line to append using js?
why tf does my web page not update when i make css/html changes
i've sent the same exact folder to my friend and for him it applies the new changes for me it doesnt...
in my vscode or my browser
browser
no
How does Django's template language introduce new syntax into html, do stuff with it, and not make editors scream in pain? How is it able to do that?
probably because the syntax parser has been updated to expect these kinds of templating additions
Ok, but how does it change normal HTML syntax? Some editors would probably scream, but they don't. Why is that?
if the editor is not complaining then the syntax parser being used is updated and allows for this new syntax
or it is simply legal html and the parser thinks that the templating syntax is just text within the element tags
Ty
if you want to know the real answer you should see if you can find information on the parser being used in your editor
apperently that didnt work
nvm it worked, but it only worked when i kept my dev tools open
normally css is not changing on each pageload so the browser will just cache it and use what it saw last time
I think there is some hot key like ctrl-shift-r or something which will hard refresh the page
and not use cached resources
you using any backend? to render your html
Anybody know where I could code a website using python?
What do you mean "where"?
You would use your editor/IDE
I am on a school issued chromebook and am unable to download that software ๐ข
Would I just use repli.it
You could technically use something like replit
any advice on handling routes with flask. Whenever i see projects they're usually all handled in one file but i can't help but feel this formatting is for the sake of ease for tutorial purposes
you want to use urls in another file seperated from views?
i guess im just looking for best practice as i assume people dont just use one file full of loads of @app.route urls in. unless im wrong??
yes but the decorators are there for a reason :P
they make it a bit cleaner having the routes next to the function
no difference right?
you should look at blueprints if you want to separate things into separate files
No difference in terms of how they work
the decorator is a helper function
it makes stuff cleaner
so if you started a project would you have one file handling all of them?
no, I would use blueprints
ah okay
thank you
{% extends "base.html" %} {% block title %}Profile{% endblock %}{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'login.css' %}">
<section>
<div class = "box">
<form method="POST">
<h3 align="center">Login</h3>
<div class="form-group">
<label for="email">Email Address</label>
<input
type="email"
class="form-control"
id="email"
name="email"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
class="form-control"
id="password"
name="password"
placeholder="Enter password"
/>
<a href=https://d title="Please visit our discord server to reset your password">I forgot my password</a>
</div>
<br />
<form class="form-inline">
<button type="sumbit" class="btn btn-outline-success" type="button">Login</button>
</form>
</form>
</div>
</section>
{% endblock %}
``` {% extends "base.html" %} {% block title %}Profile{% endblock %}{% load static %}
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'load'.
;0
python + html + css :c
pls help
you didnt open your block content
Had anyone used next-auth with Django, or really any other existing app? I'm having trouble fitting it into an existing schema with the custom database/model options.
I can get next.js working with a JWT but i would really like to use next-auth to take advantage of email and social tokenization.
It just feels like trying to fit a square peg into a round hole.
How do i know if the content of 2 array is the same as the other aray in js without looping
could stringify and compare
U gave me an idea
Since Javascript doesn't have it, I'll develop a third party app
@buoyant shuttle Why not just stringify them or use a loop?
Imo, you don't need a whole thing to just compare two arrays
I just made a function that uses loop and compare
It's weird js doesn't have a built in function like that
doesnโt work for certain objects
because JS uses reference equality
you would need a recursive function with cycle detection to cover all cases cases
Okey when
in the simple caseโฆ!a.map((e, i) => e == b[i]).includes(false) should work
Heyo so small question but I'm trying to send audio with flask over http post and then run it through the google speech to text api, I think I got the audio to send over fine but the google speech to text api isn't responding with anything and I was wondering if someone here could give me a hand
The client side code is thisss
import requests
BASE="http://127.0.0.1:5000/"
with open('audio.wav','rb') as file:
files={"audio":file}
resp=requests.post(BASE+"SAVAVOICE",files=files)
print(resp.json())```
and the server side is
class SAVAVOICE(Resource):
def post(self):
#request.files['audio']
audio = speech.RecognitionAudio(content=request.files['audio'].read())
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code="en-US",
)
response = client.recognize(config=config, audio=audio)
print(response)
for result in response.results:
print(f"Transcript: {result.alternatives[0].transcript}")
return {"data":"Gotcha"}
At the moment i'm just trying to get it to print it out to the server terminal but response doesn't seem to return anything
That blank line is where it tries to print out response
wow you really do have big eyebrows
maybe..cuz my app sure isn't ๐
@autumn hedge hey
I have an app with a home page, where there is a button named "Run", which when clicked will create an excel file that is stored in some location in the project folder. Now I gave a download option to download that excel file. I tried with HTML attribute
<a href="path\_to\_file" download="file\_name.xlsx"></a>
This will download the file properly. But when I try to open the file in Ms-Excel it gives an error.
Cannot open the file, the file is corrupt or file format is not supported.
First of all, I don't think you need to give the download attribute any value
Because like, it'd just be the same as the href value anyway
Second of all, did you try just opening your file directly to see if it has even got anything to do with the server?
Anyone know how to install or update a local version of Flask to 2.0.2? using pip
when i tried to include the file name in href it download with "No file" tag
and yes there is file created after clicking run in the server.
@austere relic
is that helpful?
I tried that already
thanks @austere relic
--upgrade yields the same error as well
not sure I understand?
there was a PR that was approved that should correct an issue im having https://github.com/pallets/flask/issues/4093
my app worked using an old version, but partially works after upgrading to latest Flask
can you maybe downgrade again until 2 0 1 is released?
the 2.0.x and above release are problematic
it seems like a very simple fix as well, so maybe you can just copy paste it into your version?
When I tried to include filename in href without giving any attribute to download it doesn't even download the file properly, it says file downloaded but with 0KB with tag "No file".
and replying to your second query : When i click on the run button it create the excel file in server though ans it is properly opening (hope you understood)

okay. yeah think I do
one moment
can you send the code?
i will send you the repo link wait
alright
how do i set a complex url
check dm
@app.route("/admin")
def admin():
return render_template("Admin.html")
@admin.route("/roomdetails")
def roomdetails():
return "Room Details"```
or
```py
@app.route("/admin")
def admin():
return render_template("Admin.html")
@app.route("/admin/roomdetails")
def roomdetails():
return "Room Details"```
is it this?
yes
It needs to go like this
<a href="../../../floorsheet.xlsx" download </a>
that's why it was downloading an empty file
download value is used to give new name to the file
not locate it on your pc
looks like Flask 2.0.x is multi-threaded by default
which at times will cause my application to return the incorrect response values when both ajax requests are sent out simulataneously
I have tried this earlier too. I told you that too in earlier text. It says No file
wdym?
@austere relic so much to unpack and I'm not 100% certain if its the way my app is constructed or Flask 2.0.1 itself
my work around on the frontend is the delay each ajax request by 2 secs to avoid Flask from clashing somehow when each request is sent
Thanks
Was it that?
solved issue
okay well, as long as it works
I really think its a Flask threading issue TBH.. just not sure But as I was pausing the python debugger to create this image, unpausing the process resolved each request as well. BUT as you can see the Menu data is also the same as the table data.
Hi,
Is there any advantage of using httpx module over using request module?
Yeah like if I am already using request module for one of my project
Will it make sense to switch to httpx in the long run
I am also considering community support for the module here
I think they are awfully similar
You can probably just import httpx as requests and get away with it

I might be wrong though
Ohh! I'll check this out
Can anyone please help me with heroku deployment? I want to deploy my python app, also have created heroku app, added Procfile, requirements.txt, setup.sh files to my working application repository and have also installed heroku client. Need further assistance!
Also does httpx support synchronous request execution ?
It supports both! you choose
Great! Thanks for the help๐
Can you elaborate on what you mean by complex url? Not quite understanding what you mean by your code samples either..
:incoming_envelope: :ok_hand: applied mute to @shut stratus until 2021-05-27 07:29 (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
can anyone help me with some html ...i have right src set for img tag but image wont load
can i screenshare ?
in the static folder
And then copy the link
And replace ./static/img_5terre.jpg
Like send image here or anywhere really
Right click
And copy media link
That usually works unless ur tryna upload code to web
Then it isnt the best solution
yeah but why would this not work ...this was working when i worked on this project earlier
try ../static/img_5terre.jpg
this worked thanks !
yw
Yea iv never used images from static folders
Sorry
I ususally upload to discord and copy the link
So when i send the code for review i dont have to send the images too
but why is it that it didnt work earlier with single .
folder path
yeah i wanted to do stuff locally ....later gonna use images from an API
Ye i just got used to copy link from discord... the issue is that i rely on discord to hold the images
Which has so far been decently reliable
you not accessing outside of the templates folder you actually inside templates folder(same folder) with only single .
so ./ means path will be in the parent directory of index.html i.e templates
yes
In this file or in the general of html
{% extends "base.html" %} {% block title %}Login{% endblock %}{block content}{% load static %} what block is no open
{% extends "base.html" %}
{% load static %}
{% block title %}Login{% endblock %}
{% block content %}
...
{% endblock %}
a oke
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'load'.``` I was looking for a solution to this, I followed similar steps and no effects
!PASTE
I do not know blocku does not see me or what
I don't think load is a thing in Jinja is it? Are you using something that makes load a legit syntax?
I just want to go css to html and it causes complications so I checked it on the internet and something like that came out
@drifting radish visit the jinja2 main docs probably youll find the solution. and yeah i think jinja doesnt have load tag.
ok
thank you so much
yw
need help, I have set in settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
and in project directory I have folder templates with all html file and base.html
but on web there is...this
where is my mistake?
ok I now where is issue. Dont put space between { and %
Django question - Weird thing. When I try to attach a function to a div it works fine: <div type="button" id="edit" onclick="edit('{{ post.id }}')">Edit</div>
but when I make it into a button it say Uncaught TypeError: edit is not a function
at HTMLButtonElement.onclick <button type="button" id="edit" onclick="edit('{{ post.id }}')">Edit</button>
๐ ๐
hmm
you know
that's not trivial
and
it's also not related to web development
like
have you even started on it?
or are you just like "I want help help me"
do you have javascript function named edit in your code?
oh no idea
how can i post something in a livechat via webbrowser?
hello , can somebody tell me how to reduce the font size in css by a specific percent , like 100px : 80%=80px
instead of hardcoding the font size
If you're making livechat, then websockets would probably be your best bet
x% is that size in it's container. So just set the container to 100 pixels
no the livechat already exists. but how can i send a message?
You would send a post request with the message content over the websocket, and then forward it elsewhere over a TCP connection
i want to reduce the font size when the screen is less than 800px , instead of putting a smaller font size for the "mobile version " , can i reduce it dynamically
actually i would like to post messages in a youtube live chat
yes
I'm not sure, sorry
ok thanks nevertheless
@calm plume Youtube API ?
I would advise either using @media queries or maybe (I don't know if this would work) using rem
No idea, I haven't used it
I am not aware that such an api exists.
maybe try using it . might solve your issue
Are there any cons if I use httpx over requests module?
Like I get all the advantages like async and stuff, I am just getting my head around that why one would not switch to httpx
I have a question about the directory structure for a web app. How should I organize the front end and back end code? My friend and I are working on our first web application and we want to know this.
hi, been tryna import HyperLinkIdentifyField in my django app, is anyone know to import the lib, i've checked some stuff in google but it still doesn't working..
hey I need some help , I have an issue with saving uploaded profile pics from my form to db and also static folder
hex_name = os.urandom(8).hex()
_, ext = os.path.splitext(form_image.filename)
new_name = hex_name + ext
new_path = os.path.join(myApp.root_path, 'static/profile_pics', new_name)
size = (125, 125)
img = Image.open(form_image)
img.thumbnail(size)
img.save(new_path)
return new_name```
this is the func
@login_required
def account():
form = UpdateAccount()
user_image = url_for('static', filename='profile_pics/' + current_user.profile_picture)
if form.validate_on_submit() and current_user.check_password(form.password.data):
if form.profile_picture.data:
picture_file = upload_image(form.profile_picture.data)
current_user.profile_picture = picture_file
current_user.email = form.email.data
current_user.username = form.username.data
db.session.commit()
flash('Account succesfully updated.')
return redirect(url_for('account'))
elif request.method == 'GET':
form.email.data = current_user.email
form.username.data = current_user.username
return render_template('account.html', title='Account', form=form, user_image=user_image)```
I use pilow package for image resizin and save
basically the func accepts the file name from the flaskform and somehow it does not save it
Set up a websocket server and send message content over TCP connections
maybe save the image first, then resize it then delete the original copy and keep the resized copy
nope, cuz this function works well the problem is with my form it returns nothing when I select a image then submit the update on an account
so the problem is that you are receiving nothing when you submit the form?
yes
oh
Show the html
is this flask?
yes
can i see the post route?
Hey @quasi relic!
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:
