#web-development
2 messages · Page 128 of 1
@austere cloud
This is my HTML and css in part
I used this in my last project and it worked perfectly fine
how do I make a button in an html template trigger a view?
Hey so I'm currently using Flask to create a website, and I can't add images to my website. Anyone knows how to fix that?
anyone knows if it is possible to change order of attributes inside a pydantic model after they have been defined?
Please ping me if you have a reply. Thanks!
whats returned after a delete in django?
class MembersDeleteApi(generics.GenericAPIView):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = MembersSerializer
def delete(self, request, pk):
member = Members.objects.filter(pk=pk)
member.delete()
queryset = Members.objects.all()
return Response(MembersSerializer(queryset))
is this setup right?
hey guys, i know django has its own forums where you can ask django related questions and get answers in no time!
Does flask have the same thing?
I searched online for it and couldn't find it!
Hey, looking at developing APIs, how can I go about this?
I'm taking a Udacity course on backend web dev with Python. It has a whole section dedicated to API development
and it uses Postman for testing
I'd suggest using Flask for API development... https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
Has anyone worked with DRF deserialization? What exactly does this mean?
Deserialization is similar. First we parse a stream into Python native datatypes...
import io
from rest_framework.parsers import JSONParser
stream = io.BytesIO(json)
data = JSONParser().parse(stream)
what does what mean
what deserialisation is?
Well, yeah, specifically what this is:
stream = io.BytesIO(json)
basically
BytesIO wraps a bytestring object
and turns it into a stream
you can think of it as mimicking the effect of opening a file in binary mode
except the data comes from the object you pass instead of a file
bytestring is just a sequence of binary, right?
of bytes
actually I think it's called a bytes object
can't really remember
something like that
okay, so BytesIO wraps a bytestring object, what would be an example of bytestring? A data structure?
literally a bytes object
!e print(b'abc')
@vestal hound :white_check_mark: Your eval job has completed with return code 0.
b'abc'
!e print(type(b'abc'))
@vestal hound :white_check_mark: Your eval job has completed with return code 0.
<class 'bytes'>
oh wow, never knew about that one
Hello all. I have a number of Python automation scripts that I would like to "host" on a web server for others to use on my company's internal network. All I need is a way to have the scripts passed data entered by a user on a web page and then output data to that same webpage after the script runs. I am googling around and finding flask, django, cgi, etc... and getting overwhelmed by the options. Can anyone point me in the right direction? I'm wanting to do this with Apache on a RHEL server. DMs are welcome.
io.BytesIO(json) what's with the json in the parenthesis?
presumably json is a bytes object...?
do you have any webdev experience
hmm man, i barely know about bits/bytes and what have you
basically
a string
and does the stream have any significance? why would it mean by that
I understand HTML and Javascript, no experience with PHP.
consists of bytes and an encoding
because the same byte can mean different things in different encodings
so a byte is basically encoding-agnostic (BASICALLY)
and bytes are what is sent over HTTP
you don't really need to know the details
but you can basically think of bytes as raw data and the process of deserialisation as one that turns that raw data into Python objects
so you basically want a web framework, right
since this is a Python server
you can look at Flask or Django
a web framework maps routes (URLs, basically) to code (Python functions, in this case)
so you would have a route that, when accessed, takes some data, processes it, and returns a page with the results
you can look into DJango
Thank you for the response, I will start digging more into Django.
yw
I see, thank you for the explanation.
so bytes are sent over w/ requests (you can encode them in different ways to produce different strings).
So if we wanted to de-serialize json, we would have to transform it into a byte object...
what role does the stream play? To me, it sounds like it just compiles all the bytes in the object to produce a data structure
no
it's the other way round
bytes are serialised data
the json
hollup, deserialization is python -> json?
see this
so if I sent over json to my api, that's already a byte object? because everything sent over in requests is in bytes?
as in the "raw data"
so if I sent over json to my api, that's already a byte object? because everything sent over in requests is in bytes?
@native tide ...yes, but you probably shouldn’t be dealing with that directly
since you’re using DRF
yeah DRF serializers have been doing deserialization, I was just confused on that part of the drf docs
oh yeah i found what answers the question before
json = JSONRenderer().render(serializer.data)
json
# b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'
so yeah json is a bytes object
!e print('lool')
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Anyone know how can I make the change here (the description under google search result)? Built it in react btw
Looks like this is a search result from a search engine. You can add a description for your web app using meta tags. Different frameworks have different methods to specify them. You just need to find React's method.
Open the index.html file and see for that statement in the head tag and replace
I have this django constraint
class Invite(BaseModel):
class Meta:
verbose_name = 'invite'
verbose_name_plural = 'invites'
# we need an index around the invite's created_at
# column because we don't actually delete
# expired invites from the database
indexes = [
models.Index(fields=['owner'], name='invite_owner_idx'),
models.Index(fields=['box'], name='parent_box_idx'),
models.Index(fields=['created_at', 'pk_id'], name='pk_created_at_idx'),
]
constraints = [
models.CheckConstraint(
check=(
models.Q(expires_at__isnull=True) |
models.Q(expires_at__range=[models.F('created_at'), models.F('created_at') + timedelta(hours=48)])
),
name='expires_at_datetime_check',
)
]
however the second one doesnt work
I guess am not using the F datetime and timedelta functions properly
can someone please help me with that?
pls ping when help, thanks a lot!
That is what I did but I don’t see the changes appear
if I am aiming for front-end development, where should I start?
hii guys sorry im a newbie in flask , how do i use flask and push the items over to html?
What framework/toolchain do you use for web development (front/back end or fullstack) and why? I'm looking to get into this, and I basically know that Django and flask exist, and that's about it. Difficulty is of little relevance to me, I'll learn anything.
Django question:
Is there any way I can filter something like this:
Author = [1,2,3,4]
Book.objects.filter(user__pk=author)?
@honest dock Book.objects.filter(user__pk__in=author)
via templating
oh so something like return_template("index.html" , item=item)?
exactly
you have to use jinja to represent the data
and pass any data through render_template
oh so its something like this ?
<tr>
<td>{{ ingredient.getName() }}</td>
<td>{{ ingredient.getAmount()}}</td>
<td>{{ ingredient.getCost()}}</td>
</tr>
{%endfor%}
{%endblock%}```
yeah forgot the __in thank you Landi
what do you mean?
just like you passed item in previous code pass ingredients to be able to use it in the template
oh
hello guys I got some basic code with flask for a little webapp. Anyone wanna help to make something bigger out of it?
#Serializer
fields = ['id', 'post_id', 'user_liked', 'timestamp']
but when i query its not giving me the id... anyone know why?
# Serializer
class LikeSerializer(serializers.ModelSerializer):
post_id = serializers.SlugRelatedField(
many=False,
read_only=True,
slug_field='id'
)
user_liked = serializers.SlugRelatedField(
many=False,
read_only=True,
slug_field='username'
)
class Meta:
model = Likes
fields = '__all__'
#API
class LikesApi(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = LikeSerializer
queryset = Likes.objects.all()
why isnt it returning the id. not getting it front end, and not getting it in postman... i dont understand
Hey guys, I have two tr elements inside a table, the first one toggles the other, sorta like a collapse, but it won't work, any idea why?
I have something like ```jinja
<tr>
<td>
<h1> Title </h1>
<a data-toggle="collapse" href="#userTable"><i class="fa fa-chevron-down"></i></a>
</td>
</tr>
<tr>
<div class="accordion-body collapse" id="userTable">
<td>
<h1> Test </h1>
</td>
</div>
</tr>
This is inside a table
Hello so i am trying to install npm i ffmepg-static and i get this error
anyone here know JS reduce function and how to implement?
you spelled ffmpeg wrong
anyone know how to not have 7000 if statements in my get_queryset() for filtering? its getting a little out of hand
@wicked elbow can you share a snippet to demonstrate what you're talking about?
its pretty excessive... i can think of a couple things to shrink it a tiny bit
its super ugly too. i understand it, but i doubt everyone does
wooh im so close to this project to be finished! just have to set up the search and do a put request for the settings page and its all done at least all the hard stuff
Hey @native tide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
are you running in a virtual environment?
wym
well if you are using in a virtual env make sure its running before using it... ive only ever used npm in pipenv shell
im sure it could be used without the virtual enviroment, but thats what you could be missing. i dont know that specific package your installing so cant really help, just my two cents
is there a way to make a view to do an HttpResponseRedirect() without a render() in django?
that's not terrible, tbh
i can combine a couple of them, user and users for instance. i know thats not part of that just yet, but still... the front end js is even uglier lmao
Though this may not be the best place to ask but what is better for web-scraping scrapy or selenium and if possible can someone explain it to me
im not using py im using js
Yea, you can use python to create a virtual environment for it. Dont actually have to use python other then for the virtual environment. Is your package.json setup correctly? Theres a million things that could be your issue. Google specifics about your problem. Very little we can tell from your error log.
Reverse for '<QuerySet [<ShortURL: https://google.com>]>' not found. '<QuerySet [<ShortURL: https://google.com>]>' is not a valid view function or pattern name.
def page_redirect(request, url):
get_url = ShortURL.objects.filter(short_url=url)
return redirect(get_url)
```How would I filter out the QuerySet so I can get a string with `https://google.com` inside it?
If Heroku is bad, according to many people on this server, what is better to use?
I tried AWS and Firebase, but they are complicated and it didn't work in the end
And I am having a problem with Heroku sessions that I put into #help-lemon if anyone knows how to answer it
Thanks!
If Heroku is bad, according to many people on this server, what is better to use?
@scarlet latch why do they say it’s bad
Not sure
Not sure
@scarlet latch if you are just starting out, honestly, it doesn’t really matter IMO
But I am having issues that I outlined in #help-croissant
Could you try to help?
Thanks!
Could you try to help?
@scarlet latch what database are you using
with Flask for season storage
I would start with checks on the database to see if sessions are getting validated somehow
I see the session variable gets created
In Chrome dev tools
But most of the time it gets cleared on the redirect
And when I check if the user is logged in, when the session variable is cleared, I see that they aren't logged in
But they should be logged in
Anyone help me with flask? I need to save some data submitted to me in json format by user. Currently I am saving it as follows
# get json data in the request
req_data = request.get_json()
#session['data'] is initialised as a list
data = session['data']
data.append(req_data)
session['data'] = data
Is there a better way to do this ?
i am starting to learn django
any suggestions where i can learn it from?
do i have to install virtual env?
You should 100% use a virtual env. You can learn from the django docs. They are pretty good.
Playing with the API¶
Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:
/
$ python manage.py shell
We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file.
Once you’re in the shell, explore the database API:
from polls.models import Choice, Question # Import the model classes we just wrote.
No questions are in the system yet.
Question.objects.all()
<QuerySet []>Create a new Question.
Support
this is what i found on a tutorial
where do i need to write the code exactly
🥺
When you see $ before the command, that is the terminal, when you see >>> that is the python shell
it's python, the only place you can type that is the python shell
yes you have to, I am also starting to learn Django we can learn it together if you dont mind.
sure
i mean i just saw a tutorial and it didnt use virtaul env lol
it was to create a poll
Yes, I started with this, then trying my hands on watching you tube videos to expand my knowledge on specific stuffs.
good luck guys 🙂 @young oak @unique ore
Thanks, incase I have any questions i will ask on the group or ask you.
so for me I started with the docs file of Django, and if i dont understand, i go to youtube to see a visual represntation of how things are done .
ohk
I have 2 websites.
1 website is made in php with dotnet.
The other one is made with django and react.
These 2 have separate database.
Each site dashboard has an option to go over the other website.
What I want to do is whenever a user login in one of the website , and click on the link to go to the other site.
User doesn't have to login again in the 2nd site...
As in I want to create a single sign on.
Can someone guide me from where to start.
can someone explain to me the Debug=True Variable in Flask? I have a problem with flask_talisman. In development i have Debug=True and because of that flask talisman does not force SSL and i can test locally on 127.0.0.1:5000. When I push to server I set Debug to False, right? When I do this, I cannot test locally, because flask talisman forces SSL - understandably. But when I change Debug back to True I still cannot test locally and SSL is still forced
why is it like that?
Which env are you using?
i user virtualenv and simply set if __name__ == '__main__': app.run(debug=True)
how to webscrape the css elements in a webpage using BeautifulSoup??
Can anyone help me with Django? I have a webapp deployed in production, but when I change the templates(HTML) it wont load the changes...
What I tried:
- reloading Nginx
- reloading supervisor (i have gunicorn there)
hi am new to python i need help
Hello friends i have a quick question for APIs.
One of API calls is a web scraper and it has multiple steps
how can i return a message after every step?
unless you give each user an auth token only they can use as their login im not sure there is a way honestly. completely different backends
I know that if you overuse html meta redirects, google can detect your website as spam and remove it from their index. Is this the same with django shortcut redirects?
How would I connect fastapi with asyncpg?
make a connection pool
attack it to the app or vice versa
make the pool useing the startup event which is called when the loop is first started
import asyncpg
from fastapi import FastAPI
app = FastAPI()
database = None
@app.on_event("startup")
async def startup_event():
credentials = {"user": "foo", "password": "foo", "database": "foo", "host": "127.0.0.1", "port": "5432"}
database = await asyncpg.create_pool(**credentials)
@app.get("/")
async def root():
return {"id": database.fetch("SELECT * FROM bar WHERE id = 1")["id"]} # this will always return 1, just an example for question
Like this?
What is this code for?
What do you mean?
What does your above code does?
It's an example fastapi setup, I was asking ハーリさん (CF8) how to setup asyncpg (async python database interface) with fastapi (python api generator) :D
Hey @lyric jacinth!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
from flask import Flask, render_template, request
from vsearch import search4letters
app = Flask('name')
def log_request(req: 'flask_request', res:str) -> None:
with open('vsearch.log','a') as log:
print(req, res, file=log)
@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4letters(phrase, letters))
log_request(request, results)
return render_template('results.html',the_title=title, the_phrase=phrase,
the_letters=letters, the_results=results)
@app.route('/')
def entry_page() -> 'html':
return render_template('entry.html', the_title='Welcome to search4letter on the web!')
@app.route('/viewlog')
def view_the_log() -> str:
with open('vsearch.log','a') as log:
contents = log.read()
return (contents)
app.run(debug=True)
!codeblock
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
You can format the the code using the above ^
Unfortunately, I don't know much about flask
!codeblock
Also make sure to include your question :D
Hey ! Do you know about django? Very basic django?
I'm having hard time to share my code on discord
Here, I'll just format it for you
Not my code, I formatted this for @lyric jacinth.
from flask import Flask, render_template, request
from vsearch import search4letters
app = Flask('name')
def log_request(req: 'flask_request', res:str) -> None:
with open('vsearch.log','a') as log:
print(req, res, file=log)
@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4letters(phrase, letters))
log_request(request, results)
return render_template('results.html',the_title=title, the_phrase=phrase,
the_letters=letters, the_results=results)
@app.route('/')
def entry_page() -> 'html':
return render_template('entry.html', the_title='Welcome to search4letter on the web!')
@app.route('/viewlog')
def view_the_log() -> str:
with open('vsearch.log','a') as log:
contents = log.read()
return (contents)
app.run(debug=True)
thanks!! How did you do it?
```py
code goes here
```
When you do that:
print("Hello")
It gives code highlighting and a helpful indentation :D
'''py
It's actually backticks, not quotes
oh thank you so much!!
I appreciate you help very much 🙂
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
from flask import Flask, render_template, request
from vsearch import search4letters
app = Flask('name')
def log_request(req: 'flask_request', res:str) -> None:
with open('vsearch.log','a') as log:
print(req, res, file=log)
@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4letters(phrase, letters))
log_request(request, results)
return render_template('results.html',the_title=title, the_phrase=phrase,
the_letters=letters, the_results=results)
@app.route('/')
def entry_page() -> 'html':
return render_template('entry.html', the_title='Welcome to search4letter on the web!')
@app.route('/viewlog')
def view_the_log() -> str:
with open('vsearch.log','a') as log:
contents = log.read()
return (contents)
app.run(debug=True)
the log_request function is suppose to create a log file(vsearch.log) but instead it creates a text file(vsearch.txt). Can someone figure out what's the deal here?
yes that would work, however i would recommend subclassing the FastAPI class and adding a custom database attr to avoid globals
I could use some help with django templates! I change the html code but the changes wont refresh on the site
Still have problem?
Yes... I'm a bit lost...
ok whats wrong?
I made changes to a template that i extend, but I'm having issues because the changes dont show on the website
I use:
- venv
-nginx
-supervisor with gunicorn
is it deployed?
Yes
Debug is false, yes
and of course if its deployed you have to add and commit changes if its like heroku
add and commit changes to github
I dont use heroku, my app is hosted on AWS manually
did you init any github repo?
I'm using my own github
Sounds good, thanks :)
That my branch is up to date
did you commit your changes
Yes
Yep
i hope its how i think
i would also use the databases library instead of asyncpg for easier implementation (https://fastapi.tiangolo.com/advanced/async-sql-databases/) and (https://www.encode.io/databases/)
made by the same people who created starlette
which fastapi uses under the hood
as the web server
(also sorry for the ping in the reply, forgot to turn it off lol)
i checked it. i think nginx is a bit diff. wish i could help
Is there any trick to use django and venv?
i have created few small projects before
and I never had issue with ModuleNotFoundError: No module named 'searchtime'
this time I'm using venv (activated)
@nimble epoch done it! It was something related to messed up versions on my git, thank you for pointing me in that direction!!
Im a newbie with venv but have you installed that module with pip inside of the venv?
I have created application with django-admin
added it to installed_apps
same way as I always did
Are you saying like this?
class App(FastAPI):
def __init__(self, *args, **kwargs):
self.database = None
super().__init__(*args, **kwargs)
app = App()
@app.on_event("startup")
async def startup_event():
credentials = {"user": "foo", "password": "foo", "database": "foo", "host": "127.0.0.1", "port": "5432"}
app.database = await asyncpg.create_pool(**credentials)
@app.get("/")
async def root():
res = await app.database.fetchrow("SELECT * FROM bar WHERE id = 1")["id"]} # this will always return 1, just an example for question
return {"id": res["id"]}
Couldn't I do the same without subclassing FastAPI? So, everything is the same except I remove the class and app = FastAPI().
you can but depending on the planned size of your app your linter wont pick it up over multiple files
Ah, yeah, thanks :)
!warn @strange gorge don't post ads/scams whatever that was.
:incoming_envelope: :ok_hand: applied warning to @strange gorge.
Hello, I would like to ask for Django, my models.py is:
# Tag
class Tag(models.Model):
name = models.ManyToManyField(Translation, related_name='tag_name')
def __str__(self):
return str(self.id)
# Language
class Language(models.Model):
name = models.CharField(max_length=420)
abbreviation = models.CharField(max_length=420)
# Translation
class Translation(models.Model):
text = models.CharField(max_length=420)
language_id = models.ForeignKey(Language, on_delete=models.CASCADE)
My stacktrace: https://paste.pythondiscord.com/umetehajot.sql
The models.py is only a snippet of code. I think I made the right copy and paste for you.
And the views.py
can someone help me with this error : File "/app/by_page.py", line 318, in bypage plt.imshow(wordcloud, interpolation='bilinear') File "/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py", line 2731, in imshow sci(__ret) File "/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py", line 3102, in sci return gca()._sci(im) File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py", line 1856, in _sci raise ValueError("Argument must be an image, collection, or " ValueError: Argument must be an image, collection, or ContourSet in this Axes
this is line 318 plt.figure(figsize=(10,5))
im trying to upload a wordcloud
My views.py:
def default_similarity_call(item, search_string, tags, and_or):
tmp = item.objects.\
annotate(tagsagg=StringAgg('tags__tag_name', delimiter=', ', ordering='tags__tag_name')).\
annotate(
distance=TrigramSimilarity('name', V(search_string)) + TrigramSimilarity('tagsagg', V(search_string))).\
filter(distance__gte=0.2)
if len(tags) > 0:
query = Q(tagsagg__contains=tags[0])
for i in range(1,len(tags)):
if and_or == "and":
query = Q(Q(tagsagg__contains=tags[i]) & query)
elif and_or == "or":
query = Q(Q(tagsagg__contains=tags[i]) | query)
tmp = tmp.filter(query)
return [(item.distance, model_to_dict(item), item.tagsagg) for item in tmp]
flask question:
Is there a way I can get the terminal output and display it for the user in the front-end(UI)
for example, in my webapp, when I click run on the site, a certain output is displayed in the terminal
my questions is: can I get this result to display for the user to see?
Ik this is a weird question, but it would make my site more user friendly believe it or not!
yes
you need to redirect stdout
also, you need a way for the server to send data
so either WebSockets or SSE
or some sort of polling
Hi Can anyone give me some insight into whats causing this error ? Im using Django 3.1.4 and python 3.8.6
trying to do a project from testdriven.io
import os missing somewhere?
no import is settings.py
...are you Neil
you need an import os in it.
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
thats in manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
thats in manage.py
any recommendations ?
any recommendations
hey does anyone know how to fix a dependency management issue with pipenv?
I'm trying to install Twilio but it conflicts PyJWT with social_auth_django
this is my pipenv graph : ( only included the part where problems are quite evident )
social-auth-app-django==4.0.0
- six [required: Any, installed: 1.15.0]
- social-auth-core [required: >=3.3.0, installed: 4.0.3]
- cryptography [required: >=1.4, installed: 3.3.1]
- cffi [required: >=1.12, installed: 1.14.4]
- pycparser [required: Any, installed: 2.20]
- six [required: >=1.4.1, installed: 1.15.0]
- defusedxml [required: >=0.5.0rc1, installed: 0.6.0]
- oauthlib [required: >=1.0.3, installed: 3.1.0]
- PyJWT [required: >=2.0.0, installed: 1.7.1]
- python3-openid [required: >=3.0.10, installed: 3.2.0]
- defusedxml [required: Any, installed: 0.6.0]
- requests [required: >=2.9.1, installed: 2.25.1]
- certifi [required: >=2017.4.17, installed: 2020.12.5]
- chardet [required: >=3.0.2,<5, installed: 4.0.0]
- idna [required: >=2.5,<3, installed: 2.10]
- urllib3 [required: >=1.21.1,<1.27, installed: 1.26.2]
- requests-oauthlib [required: >=0.6.1, installed: 1.3.0]
- oauthlib [required: >=3.0.0, installed: 3.1.0]
- requests [required: >=2.0.0, installed: 2.25.1]
- certifi [required: >=2017.4.17, installed: 2020.12.5]
- chardet [required: >=3.0.2,<5, installed: 4.0.0]
- idna [required: >=2.5,<3, installed: 2.10]
- urllib3 [required: >=1.21.1,<1.27, installed: 1.26.2]
twilio==6.51.0
- PyJWT [required: ==1.7.1, installed: 1.7.1]
- pytz [required: Any, installed: 2020.4]
- requests [required: >=2.0.0, installed: 2.25.1]
- certifi [required: >=2017.4.17, installed: 2020.12.5]
- chardet [required: >=3.0.2,<5, installed: 4.0.0]
- idna [required: >=2.5,<3, installed: 2.10]
- urllib3 [required: >=1.21.1,<1.27, installed: 1.26.2]
- six [required: Any, installed: 1.15.0]
but what do I do next? how do I resolve this issue?
Hi gm, do you have any recommendations on how i should proceed ?
Any recomendations you would consider ?
first
no need to keep pinging people...
anyway
you need an import in your settings.py
I’m running Django via docker-compose. When I use the dev compose file css works fine. When I use my prod compose file css stops working. All other static files (images etc) work fine but this does not. Any ideas what I’m doing wrong in prod?
not working in what sense
If I have h2 set to green h2 appears green with the dev file. When I deploy with prod file h2 is black.
are the CSS files actually loaded?
I mean... css works in the dev file
So yes?
H2 appears green when I use the dev file to deploy, and nothing else changes besides a few security settings in the prod compose file
no
I mean
inspect the page in web console
check what files are loaded.
Oh gotcha, thank you.
If they aren’t loading what setting might trigger them to not load? Any off the top idea?
Ok, lol. Thanks haha I’ll check the web console
Hi could someone review my project: https://github.com/InsaneMiner/Lemon
cool
unless you give each user an auth token only they can use as their login im not sure there is a way honestly. completely different backends
@wicked elbow
found something called SAML. Might be implementing that.
just curious, anyone in here coming from drupal?
Hello i made a mailing app(frontend)
how can i connect it to Outlook
is it possible
hi
can we run flask app under djano app
or if my flask app run on 1st vm can my django app directly access to flask app index.html page ?
@glad patrol your project's name is mdd
but i am trying to link css with html page
like this
<html>
{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}" />```
its not working
my css is not linnking with html
i dont remember much of django now but did u set STATIC_URL ?
<html>
{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}" />
<body>
<div class="container">
<div class="row it">
<div class="col-sm-offset-1 col-sm-10" id="one">
<p>
Please upload documents only in 'pdf', 'docx', 'rtf', 'jpg', 'jpeg', 'png' & 'text' format.
</p><br>
<div class="row">
<div class="col-sm-offset-4 col-sm-4 form-group">
<h3 class="text-center">My Documents</h3>
</div><!--form-group-->
</div><!--row-->
<div id="uploader">
<div class="row uploadDoc">
<div class="col-sm-3">
<div class="docErr">Please upload valid file</div><!--error-->
<div class="fileUpload btn btn-orange">
<img src="https://image.flaticon.com/icons/svg/136/136549.svg" class="icon">
<span class="upl" id="upload">Upload document</span>
<input type="file" class="upload up" id="up" onchange="readURL(this);" />
</div><!-- btn-orange -->
</div><!-- col-3 -->
<div class="col-sm-8">
<input type="text" class="form-control" name="" placeholder="Note">
</div><!--col-8-->
<div class="col-sm-1"><a class="btn-check"><i class="fa fa-times"></i></a></div><!-- col-1 -->
</div><!--row-->
</div><!--uploader-->
<div class="text-center">
<a class="btn btn-new"><i class="fa fa-plus"></i> Add new</a>
<a class="btn btn-next"><i class="fa fa-paper-plane"></i> Submit</a>
</div>
</div><!--one-->
</div><!-- row -->
</div><!-- container -->
</body>
</html>```
yes i set static url
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
'diseasepredictor/static',
]
inside your app create a static folder then create a folder with same name as your app
eg: abc/static/abc
i create
did it work ?
not working
its not getting the css file
is this correct
{% load static %}
<html>
<link rel="stylesheet" href="{% static 'style.css' %}" />```
{% load static %}
<html>
<link rel="stylesheet" href="{% static 'abc/style.css' %}" />```
abc is your app name
my app name is mdd or disease-predictor-master ?
"GET /static/mdd/style.css HTTP/1.1" 404 1663
ok
Folder PATH listing for volume New Volume
Volume serial number is 60C9-826F
E:.
├───.idea
│ └───inspectionProfiles
└───mdd
├───.idea
│ └───inspectionProfiles
└───mdd
├───.idea
│ └───inspectionProfiles
└───disease-predictor-master
├───diseasepredictor
│ └───__pycache__
├───static
├───staticfiles
└───templates
it gives me "GET /static/style.css HTTP/1.1" 404 1651
i write tree it gives me above output
then your not in the root
i am in the root of folder
pls dm me
guys what is the best framework for web development in python ?
for aiohttp, how do i use a on_response_prepare handler and a middleware
trying to catch the http_exceptions.BadStatusLine whenever the api is called incorrectly with the wrong method (HTTPS)
Hello, I would like to ask, what does this line do:
annotate(tagsagg=StringAgg('tags__tag_name', delimiter=', ', ordering='tags__tag_name')).\
What is 'tags__tag_name?
According to the documentation:
class StringAgg(expression, delimiter, distinct=False, filter=None, ordering=())¶
Returns the input values concatenated into a string, separated by the delimiter string.
delimiter¶
It's expression
can someone please help me here?
thanks a lot!
why would you want to do that
Hello, does anyone know what is wrong in this screenshot:
It seems I don't know much about Postman
can someone please help me
JSON decode error in your view for url /api/searchTrigram/
says it at the bottom
Yes this line:
File "/mysite/backend/views.py", line 1441, in trigram_search
tags = loads(request.query_params.get('tags'))["tags"]
But I don't see any problem here.
what is the use of role attribute in tags like <div class="navbar" role="navigation">?
Does it explain what that tag would do? kinda like its function/use/role?
tag me to notify please
in django the file isnt being encrypted before storage
class DefaultStorage(storage.FileSystemStorage):
def __init__(self):
super(DefaultStorage, self).__init__()
self.encryptor = Fernet(settings.ENCRYPTION_KEY)
def _save(self, name, content):
encrypted = self.encryptor.encrypt(content.file.read())
content.file.write(encrypted)
print(content.file.read() == encrypted)
return super(DefaultStorage, self)._save(name, content)
why?
the print statement also returns false
I think I am reading and writing the file wrongly. Can someone pls help me?
me?
can someone please help me here too?
thanks a lot!
you are transferring JSON within a post request, right? Access it with request.data
I’m learning Django now. I have basic knowledge of templates I wonder if I have to definitely use DjangoForms in real time apps. I’m learning Django to connect to React anyways. So I just wanted to get over with. what are the basic things I should learn?
hey, I think django is. It's heavier than Flask, and I am starting my first django project right now. It's not easy, I've done one Flask project, and now about to do a about four django projects from the book Django 3 By Example. It certainly is more intense than Flask.
It sure is heavier and has a lot of boilerplate code to start with
@opal bramble learn django rest you will get it
It is. I am really looking for some people to work on a django project together. I think it could be a better way of learning, though I am newbie but learning fast. The book I mentioned is great, but tough on your own.
Django is kinda old don't you think? It's a very good framework but there is a lot more to work with like flask and fastAPI which I found much easier to work with
old but not outdated.
Sure thanks. I'll give it a try.
yes, Django seems to be in big demand.
It is longer. It's around 580 pages or something.
yup, but really good and thorough. I am only on page 30! haha but plugging away
I am a newbie in programming and I learned to code with python and loved working with web frameworks , I worked with webpy which I found out it's not that popular, but I loved working with it and I learned alot, but I wanna to be able to work with other frameworks too, I think django is the first option , and secondly flask and fastAPI. is it good idea to work with all of them or just focus and master one of them ?
If you learn one thing. Learning others would be similar just a few tweaks.
I found doing a flask project helped in learning django. I would not have wanted to start with django first, and that was just luck on my part.
yes, flask and django have much in common.
I would suggest CS50W. That's where I was introduced to Django. I loved the course. Try it out and decide for yourself.
thanks, I feel more confident reading the documents as I'm doing a project, it's much easier for me and I learn on the go
I have a navbar from bootstrap and I have it at the top
thing is when I extend the html base page(the one with the navbar code) to another html page
the navbar covers the content underit
how to change it so that the content will be automatically under the navbar
i
lol
Hi guys! I've just found this server... Any Flask experts around?
hey guys
I am trying to make a wordcloud in my web app
img = io.BytesIO()
wordcloud = WordCloud(background_color='white', max_font_size = 100, width=600, height=300).generate(cloud_words)
plt.figure(figsize=(10,5), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
plt.savefig(img, format='png')
plt.close()
img.seek(0)
cloud_url = base64.b64encode(img.getvalue()).decode()
plt.clf()
I do this and send cloud_url to my html template
it works sometimes and sometimes it gives an error
File "/app/by_page.py", line 318, in bypage
plt.imshow(wordcloud)
raise ValueError("Argument must be an image, collection, or "
ValueError: Argument must be an image, collection, or ContourSet in this Axes
im not exactly sure why, any ideas?
hi guys my static files aren't serving... They were working just a while ago.
I've done everything on the internet has provided.
Static root, url, dir, urlpaterns + , collectstatic. Any help would be great.
hey, I just looked over what I could regarding those courses. I cannot see much until I pay. Is there a chance you could give me a little more info on them?
They have some tutorials on YouTube, CS50
ok, thanks
cheers
does anyone know how to hack in console and show correct answers in edupage test?
Any specialists in Django help me out with a small function inside my model? #help-honey
Hi, I am passing blogs object from view to template, which is all blog objects from the model. In template file, I have looped over all blogs and implemented them in cards. However, I want to restrict the blog.description to some word limit to show them as snippet. But, doing <p>{{ blog.description[:140] }}</p> seems illegal in django template. how can I achieve what I am trying to do?
with custom template filters it could work
https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/#writing-custom-template-filters
{% if 'category' in request.path %}
{% for item in posts %}
<h3>{{item.category}}</h3>
{% endfor %}
{% else %}
<h3>ALL POSTS</h3>
{% endif %}
How to break a loop after the first item?
I need ot loop through it, but want to stop after the first item
@past cipher
{% for item in posts|slice:":1" %}
thanks @honest dock
@past cipher no problem mate
has anyone done any webscraping or headless browsing on facebook?
I have a friend who posts like 8 posts a day, and I want to see something they posted six months ago
it would take me hours of scrolling to get there, but I'm wondering if I can make a python script that would just grab all of the may-june posts from their feed
on the website you can filter by year and month
it looks like you can only do that for your own profile, not for your friends posts unless they posted on your wall
I see it for my friends' posts but maybe it's a feature that is rolled out to some users and not others or something.
In any case, sure you can write a python script to do that. It could use selenium and like, scroll down the page forever or something janky like that.
I'm sure this kind of thing is against their tos though so tread carefully
Is using 64 characters to sign my JWT tokens an overkill?
hey guys i was wondering if anyone can help me setup a postgresql connection to my flask app
having some trouble
I wouldn’t think so, the more security the better
yeah I guessed as well but it looks like it ain't according to spec because my headers are unreadable when I put it like that
I am using drfsimplejwt and I'm wondering how often should I refresh the access and refresh tokens currently I have: 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30), and 'REFRESH_TOKEN_LIFETIME': timedelta(hours=6). is that ok? what happens if both tokens expire while the user if offline? will they have to log in again next time they want to use the website? not sure if I should stick to JWTs or use another method of authentication. any help is appreciated
refresh token's should be used for longer
I have an endpoint where an user can give a valid access_token and get a new one, don't use refresh ones myself
but for example gmail's refresh tokens last until you change password
are u also using drfsimplejwt?
no, jose
is that related to django?
nope, fastapi
but you can prob. use it in django just that I don't have experience with it
oh I see, isn't it a security problem to have a refresh token that lasts very long?
probably, but the spec is complicated it really depends on the implementation
Thank you so much, Would it be okay if I @ you or DM you if I have another question? I am very new to using JWTs, if not then I completely understand, thank you anyways
I am very new as well, I am refactoring one of my API's to use JWT for the first time
oh, all good
good luck with that btw 🙂
Hi Folks,
Coming from PHP background, been heavily using PHP frameworks with some orchestration (composer, etc) tools alongside with Docker.
I see some differences here and there but I find overall concepts are similar..
Just started learning Django today and I am trying to build some workflow similar to what I've been doing for a while.
- Dockerizing application
- Frontend layer (React, etc)
- Configuration Management
I think I figured out #1, and #2 but would like to get some help on #3 part. What is the Django/Python's idiomatic way of managing the configuration workflow? for example, dev vs staging(Prod), use of settings.py, SECRET KEY?, and etc...
Any help would be appreciated, of if you can direct me to the good online resource that would be wonderful!
Thanks!!
I personally have a common settings.py
that imports from settings_dev and settings_prod depending on the situation
@vestal hound thanks, is that a module that I need to install?
huh?
no
those are other files
also in the project directory
ah, I see just different config in different files gotcah
so in your settings.py, add some checks to determine local vs stage, etc? yeah ?
exactly, set some environment variables and load different configs for each one
Gotcha
as for SECRET_KEY, do you just inject it on build time? like pass in as a parameter?
i.e say if you have some sort of CI tool..
personally I also have that as an environment variable
for CI, I don't think it matters if it's hard coded into the settings_ci.py file or whatever it is
makes sense, thank you I think I gotta start with settings.py file
yeah, so if you set the DJANGO_SETTINGS_MODULE environment variable to project_name.settings_ci
I believe that will tell django to use the settings_ci.py file you create
for example
Hello everyone, I was wondering if someone could assist me with my django project. I am attempting to implement the django rest framework, and have build a class. The goal is to take the input to api/tickers/<PK> (i.e PK = MSFT) and return intraday results from my other model
class TickersAPI(viewsets.ReadOnlyModelViewSet):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = StockIntradayDataSerializer
def get_queryset(self):
item = self.kwargs.get('pk')
ticker_obj = StockTickers.objects.filter(ticker=item).get()
return StockIntradayData.objects.filter(owner=ticker_obj)
by going to api/tickers/MSFT the DRF gives me back a "detail": "Not found."
is ticker the primary key?
maybe you want to do filter(id=item)?
you can also forego the separate queries by searching through the related field like
StockIntradayData.objects.filter(owner__id=item)
also I think there's a get_object method you want to override instead
but I'm not sure
ticker is the only field in that model
class StockTickers(models.Model):
ticker = models.CharField(max_length=5, blank=False, null=False, editable=True)
class Meta:
pass
def __str__(self):
return f'{self.ticker}'
which i am using to filter by name, I know its probably not the best, but its the most relatable way to get it, (at least human readable) idk... so we need to get that in order to get the id, since the objects in StockIntradayData are associated to the id of the named ticker. If that makes sense
class StockIntradayData(models.Model):
owner = models.ForeignKey(StockTickers, on_delete=models.CASCADE)
data_datetime = models.DateTimeField(auto_now=False, blank=False, null=False, editable=True)
open_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
high_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
low_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
close_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
volume = models.IntegerField(blank=True, null=True)```
I had the get_object override working when I had it configured to just find the ID and Ticker in the StockTickers model, but the end goal here is to give tickers/MSFT or whatever ticker and get back a JSON list of intraday data (preferably even then more filtered based on other user information)
router = DefaultRouter()
router.register(r'tickers', TickersAPI, basename='TickersAPI')
urlpatterns = [
path("trade/import", tradeImportView, name="import-view"),
path("trade/", view=trade_list_page_view, name="trade-list"),
path("trade/detail/<pk>/", view=trade_detail_page_view, name="trade-detail"),
path("trade/edit/<pk>/", view=user_edit_trade_notes, name="trade-edit"),
path("trade/detail/<opk>/execution/<pk>", execution_edit_view, name="execution-edit"),
path("dashboard/", view=dashboard_page_view, name="dashboard"),
path("journal/", view=journal_page_view, name="journal"),
path("reports/", view=reports_page_view, name="reports"),
path("dayProfitLossChart/", dayProfitLossChart, name="dayProfitLossChart"),
path("oneminbarchart/s=<symbol>d=<trade_date>", oneminbarchart, name="oneminbarchart"),
path("TestChart/s=<symbol>d=<trade_date>", TestChart, name="TestChart"),
path('api/', include(router.urls)),
]
but I'm guessing ticker/<pk> is expecting to return a single object
so is this view in the router.urls?
I'd like to see that urls file
Well, DRF uses the routers, at least for class viewsets from what I am learning. Without that, I could do normal def / function based. but the routers are supposed to make it "scaleable" per say
you may want to search with a query param instead like /api/tickers?ticker=MSFT
api/ ^tickers/$ [name='TickersAPI-list']
api/ ^tickers.(?P<format>[a-z0-9]+)/?$ [name='TickersAPI-list']
api/ ^tickers/(?P<pk>[^/.]+)/$ [name='TickersAPI-detail']
api/ ^tickers/(?P<pk>[^/.]+).(?P<format>[a-z0-9]+)/?$ [name='TickersAPI-detail']
api/ ^$ [name='api-root']
api/ ^.(?P<format>[a-z0-9]+)/?$ [name='api-root']
and then grab that out of the get_queryset method
so I get that if I type api/asdasda or whatever, since the router dynamicalls generates the url paths for it
right so the tickers/<pk> is internally calling get_object and returns a single thing
but you don't have a StockTicker with primary key = MSFT
so it returns not found
thats why we get the ticker_obj too, and that is what the return should be using
I have most of the def I wrote gone, but saved this from it, if I hardcoded this, it worked and returned the JSON object of all the TSLA intraday data, but I am not trying to return the entire DB at once....
symbol = 'TSLA'
ticker_obj = StockTickers.objects.filter(ticker=symbol).get()
queryset = StockIntradayData.objects.filter(owner_id=ticker_obj).all()
serializer = StockIntradayDataSerializer(queryset, many=True)
return JsonResponse(serializer.data, safe=False)```
you can try it like this
class TickersAPI(viewsets.ReadOnlyModelViewSet):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = StockIntradayDataSerializer
def get_queryset(self, *args, **kwargs):
ticker = self.request.GET.get('ticker')
qs = super().get_queryset(*args, **kwargs)
if ticker:
qs = qs.filter(owner_ticker=ticker)
return qs
and then go to
/tickers?ticker=MSFT
that's fine
AssertionError: 'TickersAPI' should either include a querysetattribute, or override theget_queryset()method.
which I dont understand because we are overriding the method
maybe super() isn't defined?
def get_queryset(self, *args, **kwargs):
ticker = self.request.GET.get('ticker')
qs = StockIntradayData.objects.all()
if ticker:
qs = qs.filter(owner_ticker=ticker)
return qs
I think it should be but we can just write in our queryset explicitly
ValueError: Field 'id' expected a number but got 'MSFT'.
ok
but I don't know if that's the issue still
worked?
nice!
Now to just add more kwargs I guess
yup so you can add whatever you want
to the query params
and just keep filtering/sorting in the get_queryset method
The end goal here is for me to load a chart that has my trades, but a trade has multiple executions, i.e. I bought 2 shares and sold 2 shares an hour later, so I only want the intraday data for that day to plot on a chart, v.s. spending compute and DB query time pulling everything (as it does atm)
so you'll be able to query with start and end times as well and filter your querysets with those start and end datetimes
Thank you for your help @indigo kettle
np!
in aiohttp anyone know how to use on_response_prepare
for when someone uses like HTTPS on a HTTP API
hey everyone, anyone knows a way to make so only one validator of a Django Field is required?
what is flask used for in web dev
Hi guys so basically I have a problem. Currently the static files aren't serving, but a while ago it did. I tried everything I could find on the internet but no success. Any suggestions?
It is web dev. It’s a web framework that takes care of things go out and come in.
downloading a file from a server is a post request?
hello guys, i there any way in Django rest to serialize datetime object?
DateTimeField should serialise them by default
So guys I am trying to configure apache with django for production here.
However, I am not able to serve media files.
https://stackoverflow.com/questions/65807289/django-configure-apache-to-serve-media-and-static-files
can someone please help me on s.o.?
Thanks a lot for your time!
So I have apache and mod-wsgi installed on windows. Now I need to configure apache to serve django's media files.
urls.py
from django.urls import path, include
from django.conf import settings
from
or here also, can someone please ping me when help?
How do i run my py script on my website with cgi
i can't get to upload files using flask restful to work
How do I make this ? stuff with flask?
this is what i tried:
@app.route("/password?length=<nbytes>")
def password(nbytes:int):
nbytes = request.args.get('length')
password = secrets.token_urlsafe(int(nbytes))
return jsonify({"password":password})
if you didn't get what i mean:
most of the people who make api's and stuff have routes like this /password?length=someint - here user can enter any integer they want. I know how to make dynamic url like this password/5 - where 5 is length but I have no idea about passing the length variable.
i get a 404 with the above written code
That's a GET request with a query string
Those are the terms you want to google
You don't put it in the route
It would, but my data look like this {'DATETIME_ADDED': datetime.datetime(2019, 12, 10, 13, 4, 7, 916000), 'QUERY_RAW_PHRASE': 'kabel', 'ITEM_COUNT': 66908, 'LOG_TIME': 1261}
Hello, I follow the django polls tutorial but when I do this :
I have this error:
Can someone help me please ?
Did you create question_text in the models.py file with the class?
did you remember to makemigrations after you altered your model?
Hello. I just started making a website and could use a decent bit of help with one section I'm trying to implement. If anyone would be able to help me it would be more than appreciated.
hey does anyone know anything about bs4 and chromium that can help me with an SSL issue
it started to do this out of the blue, its been working before but its a web scraper and im wondering if something got updated and changed the SSL and now it wont work
can someone join me in help-aluminum. I have an issue with Django communicating to a postgresql database, i dont know why
Anyone know how to reference a url from a Django Rest Framework router inside an HTML template?
i.e. {% url 'appname:api' arg1 arg2 %} ?
How can i write a api/auth test in postman? I cant fix is
You can make request to your API in postman
what's the issue?
i have the same problem as that guy but I don't get how did he resolve, the answer was ```
You are using a WebSocket client to connect to a Socket.IO server. Use a Socket.IO client and you will be fine. WebSocket is not the same as Socket.IO, the latter is implemented on top of WebSocket and uses a different protocol.
I have Flask application and I want to use flask-socketio to handle webosockets with gunicorn and eventlets.
Although, when I try to connect my test client (http://www.websocket.org/echo.html) I am
Does anyone know a good website or youtube video where I can see how I can test my webshop login in postman?
The issue is not with postman, it is with your view
So what I'm doing is right? only put the url in it? "http://127.0.0.1:5000/api/auth"
Shouldn't I include key & value? or a token
Postman is for requests... you can edit that request to your needs, like if you want to include JSON in the body, have headers, etc.
You can add your tokens/headers/whatever within postman
bro ngl its an issue with your server code rather than postman
postman is showing that your code is crashing
^
Plus you got the error NoneType object is not subscriptable
4xx codes are you fucked up
2xx codes are okay
3xx codes are yeet ya to somewhere else
2xx error 🥴
In flask caching, how can I get the last updated time of a cached object?
Hi all, I am having an issue with arguments in my django rest API. I am passing ?ticker=TSLA but I am getting back everything from the initial queryset, like the filter is not happening.
class TickersAPI(viewsets.ReadOnlyModelViewSet):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = StockIntradayDataSerializer
def get_queryset(self, *args, **kwargs):
qs = StockIntradayData.objects.all()
ticker = self.request.query_params.get('ticker', None)
if ticker is not None:
qs = qs.filter(owner__ticker=ticker)
return qs
def get(self, request, *args, **kwargs):
return Response({'something': 'my custom JSON'})
def list(self, request, *args, **kwargs):
return_list = []
ticker = self.request.query_params.get('ticker')
print(ticker)
qs = StockIntradayData.objects.all()
print(qs)
if ticker:
qs.filter(owner__ticker=ticker)
print(qs)
for execution in qs:
data_datetime = execution.data_datetime
op = execution.open_price
hp = execution.high_price
lp = execution.low_price
cp = execution.close_price
data_dict = {
"x": data_datetime,
"y": [op, hp, lp, cp]
}
return_list.append(data_dict)
return Response(return_list)```
is this the correct channel to ask for web scrapping?
@silver grail if ticker is not None:
qs = qs.filter(owner__ticker=ticker) does this do anything?
1 sec, sorry was out
I have the same question... Looking to hire someone to create one for me.
Well yes I would assume anything that related to Web can be asked here.
hiring someone? im not too sure
@zinc hill it does the same thing still. i.e returning all the results in the formated response. i.e. I give ?ticker=TSLA and it gives back all objects for MSFT and TSLA (only two I have data for in the DB )
The first print(ticker) is printing a string as expected, but both print(qs) are showing the same output
what happened if you do
qs = qs.objects.filter(owner__ticker=ticker)
AttributeError: 'QuerySet' object has no attribute 'objects'
oh sorry
i mean
qs =
StockIntradayData.objects.filter(owner__ticker=ticker)
oh i guess it does work yourway i didnt know that
just returns an empty list
I should note that the owner is tied to the Ticker string of ticker in another model. I.e. StockTickers has ticker = charfield where I store all the tickers and then the intraday results are ForeignKey'd to StockTickers
I figured that was more efficient than querying for a string every time. So that is where the owner__ticker comes in, although I am ignorant as to how it works
wait
def get_queryset(self, *args, **kwargs):
qs = StockIntradayData.objects.all()
ticker = self.request.query_params.get('ticker', None)
if ticker is not None:
qs = qs.filter(owner__ticker=ticker)
return qs
does this work?
@silver grail
erm idk. It just yells at me if it is not there, basically neither the get)queryset or the list def are filtering as expected
wait whats the different between def list and def get_queryset?
Nothing. But the rest framework breaks if I do not define a queryset anywhere
either via a queryset = StockIntradayData.objects.all()
or overriding the get_queryset function
ok can you comment your codes? and follow this code
Ok
class TickersAPI(generics.ListAPIView):
serializer_class = StockIntradayDataSerializer
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
queryset = StockIntradayData.objects.all()
ticker= self.request.query_params.get('ticker', None)
if ticker is not None:
queryset = queryset.filter(owner__ticker=ticker)
return queryset
this is just a piece of code from the doc
i just wanna see if it would work to begin with
Same thing
hold on
Hey guys, I have couple questions about Selenium.
Is this the right place to ask about it?
Failed to execute 'evaluate' on 'Document': The string '//span[contains(translate(@title)='Dd')]' is not a valid XPath expression.
any solution?
can someone help with this please
#ot0-fear-of-python message
Alert-warning will give it a red colour when it is displayed
You can also do alert-sucess and it would give the alert a green colour
Hello, I send a variable (connect) on my template with quart containing the status of the user and there puts in: <img src="{{ url_for('static', filename='assets/IconDiscord/{connect}.png')}}" but for some unknown reason, it modifies the name of the image by %7Bconnect%7D.png, so it doesn't find the image, do you have an idea how to fix this?
yo
can someone tell me
what is this
like what do we call it
this #document
its inside an iframe
i dont hve tht much experience in web dev
@merry geyser this answer your question https://stackoverflow.com/a/21476147/11225821
thnk u
Hey need some help with python and regex
Im trying to split input string at \r\n and period followed by space but not after Mr/dr etc
Hi all.
I've been using marshmallow for object serialization/deserialization and I came across this piece of code:
`
from marshmallow import fields, Schema
from encrypt import encrypt_pass
class UserSchema(Schema):
class Meta:
ordered = True
id = fields.Int(dump_only=True)
username = fields.Str(required=True)
password = fields.Str(required=True, deserialize='load_password')
def load_password(self, value):
return encrypt_pass(value)
`
Now, I understand most of it but what does is the functionality of deserialize attribute inside fields.Str() apart from calling the function?
[FOR HIRE][REMOTE]
Hi, everyone.
How are you?
This is Lee from China.
https://www.linkedin.com/in/lminglai
https://liminglai.herokuapp.com
If you need a web developer please contact me.
I am well versed in
- Express, Koa, Nest, Python/Django, PHP, Laravel, AWS
- MongoDB, MySQL, SQLite
- React, Next, Redux, FunctionalComponents, Hook, Thunk, Saga
I am available and can start work right now.
Thank you.
Hi, if you're passing a value from your front end to the backend of flask. Are you "grabbing" the name you've assigned to the originating source? E.g. a input field called name. So would just do request.form.name to retrieve that value?
Hello Everyone^^
I developed a Requirement Management Website for my Bachelors Degree and wanted to hear some Opinions.
The Site is in German but I can translate things if you want.
I hope this is the right place for that.
Here is the Link: https://anforderungen-und-testen.herokuapp.com/accounts/login/?next=/aut/
Thank you in advance^^
We also have #career-advice, which might be a better place for this, since this channel is more for questions :D
hi bois , i've never done web stuff before and i thought about automating some stuff around the house with python and a respberry pi. Everything would be controlled from a webpage that runs on the pi and my question is :if i make a script that let's say turns a lightbulb on and off and i want my page to have a button that triggers that script is it enough to make that button go to a non existen link and then in django rout it to a function that just triggers the scrip and then resets the current page would that work ?
you know why the page loads infinitely (it freezes when it gets the info)
from quart import Quart
from discord.ext import ipc
app = Quart(__name__)
ipc_client = ipc.Client(secret_key="my_secret_key") # secret_key must be the same as your server
@app.before_first_request
async def before():
app.ipc_node = await ipc_client.discover() # discover IPC Servers on your network
@app.route("/")
async def index():
user = await app.ipc_node.request("get_user", user_id=640518207257444374)
return user
if __name__ == "__main__":
app.run()```
and api:
```py
import discord
from discord.ext import commands, ipc
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc = ipc.Server(self, "localhost", 8765, "my_secret_key")
async def on_ready(self):
"""Called upon the READY event"""
print("Bot is ready.")
async def on_ipc_ready(self):
"""Called upon the IPC Server being ready"""
print("Ipc is ready.")
my_bot = MyBot(command_prefix="!", intents=discord.Intents.all())
@my_bot.ipc.route()
async def get_user(data):
user = my_bot.get_user(data.user_id)
print(user)
return user.name
if __name__ == "__main__":
my_bot.ipc.start() # start the IPC Server
my_bot.run("token")
Does anyone know why I'm getting this error? I believe I've set up CORS with Flask from this post https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask
For the following ajax post request for Flask (how can I use data posted from ajax in flask?):
$.ajax({
url: "http://127.0.0.1:5000/foo",
type: "POST",
contentType: "application/json"...
Get request to my backend works but post fails
Here's the client side code sending the get request (it's in javascript)
axios
.post(`http://127.0.0.1:5000/tags/`, {
image: srcUrl
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
Here's the backend code
from imageai.Classification import ImageClassification
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return {"What's": "up"}
@app.route('/tags')
def put_tags(image):
execution_path = os.getcwd()
prediction = ImageClassification()
# prediction.setModelTypeAsResNet50()
# prediction.setModelTypeAsInceptionV3()
prediction.setModelTypeAsDenseNet121()
prediction.setModelPath(os.path.join(
execution_path, "DenseNet-BC-121-32.h5"))
prediction.loadModel()
predictions, probabilities = prediction.classifyImage(
os.path.join(execution_path, image), result_count=5)
final = []
for eachPrediction, eachProbability in zip(predictions, probabilities):
final.append(eachPrediction)
response = Flask.jsonify({'tags': final})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
I used the second answer which was
Hello. I just started making a website and could use a decent bit of help with one section I'm trying to implement. If anyone would be able to help me it would be more than appreciated.
How can I use websockets for Flask?
what's the best way to have a consistent aiohttp session in fastapi?'
Same way you would with your asyncpg pool
I need it to pass between modules, so I abstracted it to a seperate module with create and close functions
Sounds like you wanted something like my router system 🤣
class Authorization(router.Blueprint):
def __init__(self, app: FastAPI):
self.app = app
self.app.on_event("startup")(self.init_session)
self.app.on_event("shutdown")(self.close)
self.session: t.Optional[aiohttp.ClientSession] = None
async def init_session(self):
self.session = aiohttp.ClientSession()
async def close(self):
if self.session is not None:
await self.session.close()
@router.endpoint(
"/login",
endpoint_name="Discord Login",
description="Login via discord.",
methods=["GET"],
)
async def login(self, request: Request):
# ... stuff
This is what i ended up creating for my router
Does that require a different instances for each file? Or did you just create an instance of said class which you import?
its actually pretty similar to the d.py cogs and extensions system
just made to be a universal router for my web apps
so this: https://github.com/SpooderfyBot/api-interface/blob/main/main.py is the main file with it being used
this is the code itself: https://github.com/SpooderfyBot/api-interface/tree/main/router
and this the only file its used in cuz i moved a load of stuff https://github.com/SpooderfyBot/api-interface/blob/main/api/auth.py
So I thought I would share some interesting benchmarks we've found after building our own Bench marker designed to put frameworks under a more realistic load with some more features planned.
TL;DR: Uvicorn + X is definitely not the fastest server
We tested 2 Frameworks and 1 Server.
- Sanic as it's framework and server.
- FastAPI and Uvicorn as the server.
Interestingly Sanic is king when pipelining is not enabled.
Sanic overall seems to handle Non-Pipeline connections much better than Uvicorn does, Uvicorn's advantage on benchmarks like Tech Empower come from the fact Wrk is biased towards pipelined request and uvicorn although it does not directly pipeline concurrent buffers pipelines allowing it to appear to be handling more requests.
======= Uvicorn Raw =======
$ ./rewrk -h http://127.0.0.1:5000 -c 256 -t 12 -d 15s
Benchmarking 256 connections @ http://127.0.0.1:5000 for 15 seconds
Latencies:
min - 8.47ms
max - 162.46ms
median - 76.99ms
Requests:
Total Requests - 171180
Requests/Sec - 11372.99
======= Sanic =======
$ ./rewrk -h http://127.0.0.1:5001 -c 256 -t 12 -d 15s
Benchmarking 256 connections @ http://127.0.0.1:5001 for 15 seconds
Latencies:
min - 12.12ms
max - 90.91ms
median - 39.39ms
Requests:
Total Requests - 244088
Requests/Sec - 16232.20
======= FastAPI + Uvicorn =======
$ ./rewrk -h http://127.0.0.1:5002 -c 256 -t 12 -d 15s
Benchmarking 256 connections @ http://127.0.0.1:5002 for 15 seconds
Latencies:
min - 35.44ms
max - 95.92ms
median - 30.24ms
Requests:
Total Requests - 68520
Requests/Sec - 4528.04
Think this shows why its so important that you dont trust or use any benchmark that uses wrk as a means to determine your framework of choice
If you want to know why wrk is bad and why frameworks that are good at pipelining no longer mean much Wiki does a decent job in a few sentence outlining it: https://en.wikipedia.org/wiki/HTTP_pipelining
Hello, I'm looking for a phytoneer or pythonistas that could give me free tutoring. Covid has changed the way we look at the world and therefore I am learning programming to make a career change. Your efforts will not go to waste and I'm highly motivated in learning and studying which will make it easier for you to teach me.
The benefits you will get is learning how to teach and tutor with a highly willing, understanding, and adaptable student. If you're one of those rare people that values knowledge and wisdom then you shall receive it in abundance from me in return for your knowledge.
Please contact me trough PM.
Hello, can anyone help me with adding a custom domain to a heroku app which is powered by Django ?
I tried to set up the DNS target to the domain ( the domain still points to the DNS that Heroku provides but somehow it failed to connect to my website.
pretty sure heroku requires you pay premium to use a custom domain, though i dont use heroku so i cant give you an exact awnser
I have the student account with one hobby dyno available . I use that hobby dyno for my app but you know it still fails
Hey can anyone help me with a quick quote on a website im building for a friend?
Hello, I'm looking for a phytoneer or pythonistas that could give me free tutoring. Covid has changed the way we look at the world and therefore I am learning programming to make a career change. Your efforts will not go to waste and I'm highly motivated in learning and studying which will make it easier for you to teach me.
The benefits you will get is learning how to teach and tutor with a highly willing, understanding, and adaptable student. If you're one of those rare people that values knowledge and wisdom then you shall receive it in abundance from me in return for your knowledge.
Please contact me trough PM.
@Go132#2500 IMHO
that would be the least I’d expect
it’s very unlikely that anyone really good would teach you for free
well there's people who wouldnt mind being a side mentor for quick questions on issues either
well there's people who wouldnt mind being a side mentor for quick questions on issues either
@hazy night yeah, that’s the point of this server
but dedicated regular teaching...?
Hey can anyone help me with a quick quote on a website im building for a friend?
@hazy night what do you mean quote
I tried to set up the DNS target to the domain ( the domain still points to the DNS that Heroku provides but somehow it failed to connect to my website.
@flint birch are you using a paid plan?
im building a site for a friends restaurant and i was originally going to do it for free but insists on pay and I dont know what I should ask for
im building a site for a friends restaurant and i was originally going to do it for free but insists on pay and I dont know what I should ask for
@hazy night hm
on what basis would you like that assessed
simple way is come up with an hourly rate and record how long you took to build it
Oh my God I hate JavaScript
Thank God for Python
but I cannot believe this language
function multiplyTwoNumbers(a, b) {
var product = 1;
for (var i = 0; i < arguments.length; i++) {
product *= arguments[i];
}
return product
}
>>> multiplyTwoNumbers(3, 2, 2)
>>> 12
WHY IS THIS ALLOWED?
Because it's convenient in some cases.
var a = z;
a = add_one(a);
function add_one(x) {
return x + 1;
}
var z = 4;
Why allow me to name and specify the quantity of parameters
and then just treat it like a suggestion
also why is this not any sort of NameError, why does JS not do NameErrors at all
and why are all the data types named such obtuse things
I'm sorry for the rant, I'm sure I'm missing something with JS
The language follows different rules than python
but right now it's completely impenetrable to me, and I'm not really a completely junior programmer
and Python is not my only language
It mostly focuses and not crashing and in cases where most languages would crash it tries to create some sensible result
I would prefer a crash
Try typescript instead, it doesn't make that horrible mistake
Yeah, it's not a very good paradigm
but then it's just compiling to JS
I don't like all these dependencies
on what is the language you're forced to use if you want code that runs client side on a browser
Modern JS is quite nice though
I believe I'm using modern JS
var is not modern JS
I was messing around with a Node interpreter, let me check my version
Functions are still weird though
yeah I understand that now, let and const are much preferred
I didn't run into any of the issues with var that I've been told about but I'll take everybody's word on it and just not
The abstract equality operator
good God
WHY
I am doing this so that I can get a job because realistically web dev is the most accesible if you don't have a degree
So that ==1 works on html and form contents
but I shudder to think of the absolute horrors that exist in JS codebases out there
Like, there are reasons for this nonsense. Just not very good ones
I can't believe people learn JS as a first language, I would never recommend that
JS was conceptualised as a scripting language that would be used by beginners who just wanted to add some functionality to their websites and might not have formal education
accordingly, it tries to kind of work in most cases
It's not that bad, and you get to do graphical things other than turtle really soon
True
like I said, there were originally reasons
Python is great for new devs in this regard because there is just a right way to do things
shrug it's where we are now and it's too late to change many things
and the amount of absolute insanity you can do in Python is not very much
🤔
not sure about that one
because the language just puts it's foot down and says "no"
Relative to other languages
hm.
I would say that Python is relatively high on the scale of "you can do dumb things"
really only Golang is comparable in enforcing sanity
lower than C/C++, higher than Java
Rust's entire idiom is sanity
because of dynamic typing
Python manages that insanity fairly well when you have a good understanding of the language though
So does JS
when they say "everything is an object" they really mean it
and when you stop thinking of things that would be a primitive data type in other languages as a primitive data type
it makes a lot more sense
this is true in many other languages
and dynamic typing is always a source of many errors
Python is not really unique in anything.
Though decorators are probably a python feature first
It's not completely unique nor is it perfect
but it's easily my favorite mainstream programming language
and it is very mainstream
C++ is horrible as well, JS reminds me of that in some ways
there are too many "right ways" to do things, though for very different reasons
there are many right ways to do things in Python too
"there should be one and only one obvious way to do it" died a long time ago
C++ just has such a disgustingly bloated standard library that you could be using it for a year and read somebody else's program with no external dependencies and have no real idea what is going on
Consider padding strings in python
I agree, some things need to be trimmed
there shouldnt' be so many ways to format strings
most functional things can probably go honestly
I would prefer to keep the functional parts
lambda and map is usually redundant
right, but comprehensions and generators usually got you covered
and are nicer to read when it's not your code
filter is situationally useful though I would say
you don't see this much in Python, but the main point of map is composability, I guess
like
processor = flow(
map(f),
filter(g),
flat_map(h)
)
processed_data = processor(raw_data)
but yeah, I would agree
Python's map/filter are a bit weird
I probably use reduce the most
I forgot about reduce
😭
What do I do about this JS problem though, what should I do for a Python web dev stack?
mine uses Angular + Django
I'm sort of on the Flask train right now, I hear Django's learning curve is kind of steep
and I don't really like being locked into one kind of DB
I want to learn a very flexible stack
that can be scaled up and down as needed for different projects
and just get very, very competent using that stack
typescript is looking to be a must though I think, I'll have to be comitted to an asylum if I have to work with JS without it
hm
well
I mean
IMO SQL works fine
for most cases?
Yeah but it would totally be overkill for some
e.g.?
like it seems to me the cost of creating an SQL database is not really that high any more
No real sensitive or permanent user data being stored server-side, JSON is perfectly fine for that
Like I want to build out a web app that's a synced Pomodoro timer that just basically has rooms that you get a custom link for
and the only real database needs would be storing some random session specific user ids, some config settings for the session, and various information about the timer or whatever
like file storage?
or what
server-side
so
it wouldn't be client downloading JSON or whatever
in a file?
shrug like my PoV is that there's not much cost to creating a database any more
I haven't done a lot of work with relational databases
be it SQL or something like MongoDB
etc.
also, your host might not allow file uploads
or
on-instance storage might be ephemeral
most likely would be deployed to a VPS
but yeah, that would be correct for something like Heroku
So many smart people here 🤯
Not really lol
I'm sure he knows a lot more than I do
I'm really just getting started with web dev
I probably think I know a lot more than I actually do
these are just my semi-educated guesses
but yeah
Django is rather huge
and chonky
and a bit outdated.
I have heard good things about FastAPI
I think I'll probably stick with Flask
I like it quite a bit so far
for my next project
Python already has some database support in the STL
I really want to use an async native framework
so that is always an option
! STL?
C++ background?
Somewhat
❗
C is a beautiful language actually
I love C
Yes, C + Python is a thing of beauty though
Such as?
and, IMO, like Django, it's kind of showing its age
anyone know why im getting this error? UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte pulling from a ForeignKey field. its just a string to the filepath so i dont get it
where is the error coming frmo
is it passed implicitly?
being passed back from the API to my frontend. db is set up correctly because i can follow it in my db viewer
the routes object I mean, or as part of some "magic" that FLask is doing for you?
its django
there's a global request proxy
that always refers to the current request being handled (because Flask is sync)
which is just a 🥴 model to me
I mean
where in your code
going to assume somewhere in the parser or serialiser layers
I still need to learn how to into async
actually I can go do that right now, off to MDN
class PostsSerializer(serializers.ModelSerializer):
upload_src = serializers.SlugRelatedField(
many=False,
read_only=True,
slug_field="src"
)
class Meta:
model = Posts
fields = ["id", "uid", "datetime", "gid", "src", "upload_src", "description", "type", "likes", "comments"]
has to do with the SlugRelatedField im pretty sure
src is the key in both models
I also need to learn how to actually read and write SQL lol, embarrasing to say but I've been using ORMs as a crutch
I think you defo should
async is the future of web IMO
like right now I'm already running into very real problems
because DRF doesn't support async
i run async with axios. http://www.safespace.fyi:8000/ is my site. its all done async
?
huh?
why do you have a PORT in your URL
what's the relevance
the entire site is async.
...is your incoming data text or bytes
is the url just forwarding to an IP instead of you setting up CNAME stuff properly?
you're using DRF...how can it be async?
static links arent up yet
This has a bad security smell to me
I don't know exactly why because I don't have the requisite knowledge
still in developement. its up in dev so my testers can pass the errors to me
but I think sharing your debug enabled dev server is not a good idea
it lets anyone see your config, at the very least
and sending passwords and username over http is a very big no no
that much I do know
eh, its not gonna change anything, because the entire thing is gonna change once its in production.
which opens up possible attack vectors
yes, but theres no information to steal anyways. anything youll get from the dev page you can find in the js anyways. its not masked
You should still probably be emailing yourself debug messages if you're not just testing o localhost though
Hey guys, in Flask I'm wanting to receive the request value of an input field. am i fetching it by doing?
request.data.<input_fieldname> ?
Flask is the backend for my app
probably true, but eh. really doesnt change much
adding to your point, you can set up an smtp server using python
anyways
my guess is that there's an encoding mismatch
like expecting UTF-8 and getting ASCII
Using this:
python -m smtpd -c DebuggingServer -n localhost:1025
I would consider wiping EXIF data on upload
There's only one image that doesn't come from Facebook up there right now, but it looks like EXIF data isn't sanitized from the toher ones
me too
it's actually something I need to look into for my current project
I know it'll be a problem on launch but I haven't gotten around to it
pretty simple actually
no the actual removal is simple
but
okay so basically what I need to do is
on upload
verify that it's actually an image
strip metadata
create several versions
and push to storage
(oh, and this is where I would REALLY appreciate async)
Why the several version?
different sizes
Could you just save the largest size/resolution and resize on demand? Or is storage less of an issue than doing that?
That would be my first thought, offload image resizing to the client
honestly I don't know
never done this before
and sometimes it kind of feels like premature optimisation...?
but the thing is
it's defo meant to be mobile-friendly
and
assuming each image is 400 kb or so?
there are cases where
as many as 7-8 images need to be loaded at once
Is there a maximum image upload limit?
and my gut feel is that downloading a few MB of images to display a page for mobile is a bad idea
thinking 500kb or something?
there will be, but I haven't implemented that yet
What exactly are you building? '
