#web-development
2 messages ยท Page 151 of 1
Should I learn django or flask?
how can I overcome that
?
Django is better
Better just overall?
python -m pip install Django
although I would advise installing in venv
which means...
what is your OS?
Windows
python -m venv venv
venv\Scripts\activate
python -m pip install Django
in next sequence, commands then
be sure to activate your venv, when you start to work
hey guys, anyone good at react? I have a startup idea to discuss. If you are good at react dm me
pip freeze > requirements.txt
a way to... copy all your current requirements dependencies to quick install file
can someone help me with this please
please tell how to do this
pip install -r requirements.txt in just started venv, in order to reinstall them
venv\Scripts\activate
ok. got it
anyone?
Yeah, or you can chose your own name for the environment by changing the last venv in "python -m venv venv"
shrugs
standard is good one
i recorded it to my .bashrc file
alias ac='[ -d "venv" ] && . venv/bin/activate || (python3.9 -m venv venv && echo "created venv" )'
alias de='deactivate'
alias dj='python manage.py'
alias sc='python scripts.py'
in order to have quick venv activation with ac (creates venv if there is no one)
You might wanna look in a server with experienced js people
Good luck though
I cannot find anything in the docs to answer this, but was there a major change to on_delete in Django 3? I upgraded from 2 to 3 on a project (working on version 2) and I get TypeError: on_delete must be callable. on a model field that has no on_delete at all. When I add one,it states that there are multiple values for the argument on_delete. Any ideas?
the server isn't for recruitment
you're raising a 404 error, is that not what you wanted?
could someone help me to do something?
Hey guys anyone has expereince using flask and firebase
It depends on what you want to build
So what are the differences?
Flask would be better for api's
And allow more freedom in your app architecture
I would say that flask is more advanced ๐
Oh
Since you have to pick all components you want (orm, etc)
But it's more simple too
Yes, django has built-in auth, orm and admin
Yeah ok
But actually i would use fastapi over flask
For API's or just in general?
For api's
Yeah ok
If you use server rendering (jinja/django tempaltes or something like this) then i would go with django
Django isn't that great for api's
So if I want to build a web app which does not include api's Django would be the best option?
With server side rendering? ๐ค
html templates that server populates with some info and give to the client
Okayy
Statically generated sites or pre-rendering and server-side rendered applications are two modern ways to build front-end applications using JavaScript frameworks. These two modes, yet different, are often mixed up as the same thing and in this tutorial, weโre going to learn about the differences between them.
Thanks!
Scroll down to like definition of server side rendering
Again, it's like just populating your html templates with some data you have in your database
Do you have any sql knowledge?
Not much
I guess django can be easier in what comes to sql
Okay
It does many things for you
I think I'll try both out
If you would like to make use of type annotation i would go with fastapi
Yeah
And fastapi has everything flask has, so imo there's no point in using it
using flask?
Yep
Sure do
Ty!
Share your model
I think i figured it out. But regarding SSR, i love using Django but have recently learned about the benefits of Next.js. what are your thoughts on using next vs React with Django? I love python and want it for my backend but needa better solution for the front end and React seems to have poor SEO. @serene prawn
I don't have much experience with react
And i talked about template rendering really
What's your optimal solution for front end with Django then?
I know, just thought you might have an opinion. ๐
I won't really use frontend framework with django ๐
does anyone oculd help me with celery?
I'm pretty sure you can use Django with next.js, run build and then let django handle the static files. I'm not 100% sure but I think next.js creates lots of bundled files for each page rather than create-react-app which is just one client side app.
sure, what's up
Right. I'm hoping to take advantage of the caching in next to speed up my Django projects.
Guess I'll just have to try it!
NGL at that point why use Django
Django doesnt serve static content anyway (and shouldnt for that matter)
and if you're using just to make the API at that point just use FastAPI
Yep, it's so much better for apis
yeah I know it's not the best, personally I learnt django for employability and it doesn't seem like FastAPI is that sought after. But once I've had my time with django I'll 100% move over, either that or a JS backend
FastAPI is generally a very sought after backend as client side rendering becomes even more prominent
i don't doubt it, but just searching "fastapi" vs "django" for jobs and seeing what is available is what is keeping me from it
It generally depends on it
but also, if you are using next.js and want server side rendering, why not use django?
Django certainly isnt used to be an API
because it really doesnt do a great job at it
You basically dont make use of any of the pre-built boiler plate stuff, model validation is a pain and throughput isnt the best
Doing a E-Commerce site? highly cached? Sure use Django
and thats what alot of these contractor jobs do because it's quick and doesnt really need to be api based like that
but as soon as you get to API only type setups then Django kinda a meme really
Well, there's drf, but ๐
DRF 
I cannot tell you how much i hate my life when writing rest and api frameworks in Django vs FastAPI
I remember there being a django module for graphQL
As much as Django's orm is cool and all
Patryk used to recommend it
its still such a yikes compared to FastAPI or a micro framework
honestly, I have found fastAPI extremely painful once I needed to do anything that required metaprogramming
since it parses the signature
Just mod it ๐
I ended up using stalette
I actually made a framework wrapper for that tbh
so how about node.js? I heard deno is good
node is ok, but I am not fond of nodes dependency style
Deno is mostly for TypeScript because of the auto compile
but again, not recommended for prod as of yet
My experience with Node frameworks is 
ah yeah it's not the same thing, thought it was as they have the same creator
but typescript is lovely ngl ๐
Typescript is great
just alot of web frameworks suck in places, mostly cuz JS tings
bit like go tbh
as much as i like some of what Go does
i cant write backend frameworks with it
Doc strings or lack there of
I don't really know what server framework to suggest. starlette/fastAPI are probably my best bet, but ORM integration is pretty obnoxious last I saw it.
True, fastapi is really more suited to apis
ORM stuff kinda blows for async in general tbh
Atm im working on a async orm built of PyDantic
raw SQL works OK, but it is an extra hour of messing with queries per project
cuz i got so fed up of SQLAlchemy core not supporting model inheritance
another 2 if you need migrations on top of that
Tbh sometimes it's easier to write sql
sometimes
tbh I've been on the brink between django and node.js for a while
I mean learn both
what do you guys say?
but NodeJS is an entire language
its not really a HTTP framework
well, it has support for it
mhm, well specifically express
to be perfectly honest, for 90% of projects, any reasonably popular web framework will do the job perfectly
nest js seems cool ๐
what you need to do is identify which parts of your project are going to hard, and decide around those
hmm yeah that's quite true
there are some really cool things in node, like https://blitzjs.com/, but you have to figure out how its deps look and such
Wouldn't nestjs be more powerful? ๐ค
In most cases it literally doesnt matter
Its like when people argue over using a framework "cuz framework x got n score on techempower vs framework y that got n score on there"
Yeah, but nestjs makes good use of typescript and allows you to encapsulate your logic into services
so why not
I wouldn't solely rely on benchmarks ๐
benchmarks mean nothing in reality
But if one thing is ~10 times faster than other and it's similar to it then why not?
generally because it doesnt tell you the reality of the performance
Say fastapi and flask, that's nobrainer even if fastapi was the copy of flask
a framework thats really good at pipelining vs a framework thats really good a real world requests
the pipeliner will win but at a cost
Btw does sqlalchemy has async support? ๐ค
not really
there's databases or orm but they only support a very minimal amount of alchemy core
and so no model inheritance 
I guess i would stick with sync sqlalchemy for now then ๐
It mentions async support though https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html
personally i dislike alchemy
I generally dont use ORMs like that
What if
I put my web app's url in here ๐ณ
what are the chances that I get hacked
hacking intensifies
recently what i've been working on my more official ORM for pydantic
just because i see no point in a ORM without inheritance 
SQL Alchemy? ๐ณ
You would need separate models for views anyway though ๐
not really
for example what we have alot of it a entity base
then extensions of that
Exclude/Include fields, relationships?
going onto specific setups
class Entity(BaseModel):
...
class ExtendedEntity(Entity):
...
class User(Entity):
...
class Area(ExtendedEntity):
...
inheritance is by far the most powerful thing imo with ORMS 
You can live without it i guess ๐
not really 
Though there might be many use cases for it
i dont want all these duplicate models n shit
I guess i can stay on sync sqlalchemy for not then ๐ค
Though it sqlalchemy fully supports async @quick cargo
Is it okay to ping you?
Sure
It just returns weird list of Rows ๐
async def retrieve_all(self) -> List[Entity]:
async with self.async_session_factory() as session:
query = select(Entity).order_by(Entity.name).options(selectinload(Entity.children))
result = await session.execute(query)
return [row[0] for row in result.all()]
But it works ๐ค
Curious that all() isnt async tbh
It should be cpu bound ๐ค
although if i remember i think it selects all every time so ig maybe not
It shouldn't do any io
I mean generally it should be IO bound because typically you dont wanna fetch every row every time you do a query
because this works ๐ค
async def retrieve_all(self) -> List[Entity]:
async with self.async_session_factory() as session:
query = select(Entity).order_by(Entity.name).options(selectinload(Entity.children))
result = await session.execute(query)
return [row[0] for row in result.all()]
it's a small table in this case
lets say you have some massive DB with multiple matching rows, you dont always want to select all the data and send it over the network
But limit works
yeah
In my case it's a table with tags so i can safely return all of them
It wouldn't be bigger than ~50 rows and i want to display all of them in my vue frontend ๐ค
Anyway i don't like how it returns the data ๐
How can you can have multiple entities in single row?
because each row can return several column values which are apart of the row
all() returns all the rows
but each row has a set of columns
But it returns model instance ๐ค

Im guessing maybe Many to Many then
or just not use alchemy 
Raw SQL ๐ฆพ
I'm gonna go to sleep now, but leaving this here overnight:
How could I go about making a web dashboard so my bot can be controlled from there?
Please ping me if you can help, hope this doesn't break any rules lol
lets say I refactor my code into this https://gist.github.com/SkyBulk/65f3781bc9e79e26321239dda8517140 , and needs to point to https://gist.github.com/SkyBulk/92dcab544c9332e465e88b199a241669#file-async_sample-py-L18 reponse how can I use this in order to save it to postgresql ?
So I'm making an application that I want to deploy as a website and I am running around in circles unsure of what to do
It is a computatinally intensive app so it needs to connect to an AWS EC2 instance with vCPU's in order to serve the user's requests
Im just not sure what the overall structure of the website is supposed to look like
is the entire thing supposed to be within a docker/kubernetes container that starts a new instance every time a user visits the site?
There must be nothing computationally intensive on a visit of a website.
so the computation would have to be done by an API?
@app.route("/addpatient", methods=['GET', 'POST'])
@login_required
def addpatient():
v = Newpatient.query.first()
a = Totalpatient.query.first()
form = PatientForm()
if form.validate_on_submit():
patient = Patient(name=form.name.data, number=form.number.data, gender=form.gender.data, year=form.year.data, month=form.month.data,
day=form.day.data, street=form.street.data)
db.session.add(patient)
db.session.commit()
patient = Patient.query.all()
for i in patient:
if Patient.name not in i: # Error: TypeError: argument of type 'Patient' is not iterable
a = Totalpatient()
a.count += 1
else:
a.count += 0
if not v:
v = Newpatient()
v.count += 1
db.session.add(a)
db.session.add(v)
db.session.commit()```
Im not sure where i did wrong
@terse vapor
Is Patient.name nullable?
What you're trying to do then?
Im trying to do if the new patient has come to the clinic before, it will just save to db with adding 0, and if its first time here, it will add as a new patient and save to totalpatient db
the name its actually use in a different language
so in that language, there's no first or last name
Wdym
You can just query a patient by it's name from database
to see if the record is there
And you usually don't want to have duplicate rows in your database
That's a bad database design
And what are TotalPatient and NewPatient?
Totalpatient = All patients with different name, like how many different people have came
Newpatient = All records of patient
Ehm ๐ค
I still don't understand what NewPatient is
Can't you have like Patient table and PatientVisits?
its basically all patient that have came to the clinic
Why not store it in Patient?
hmmm, never thought of that
idk, I just did it this way, lol
You literally don't need TotalPatient and Newpatient ๐
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Patient:
id: int
name: str
...
@dataclass
class PatientVisit:
id: int # every database record should have an id to identify it
patient_id: int # a foreign key to Patient
# Any info you want there
date: datetime # The date for example
I think sqlalchemy can compare datetime and build queries from it
I wrote these 2 as dataclasses just as an example
Ya, i tried like
current_month_expenses = Patient.query.filter_by(patient_id=patient.id).filter(Patient.create >= from_date).filter(Patient.create <= datetime.now()).all()```
You can filter by patient id...
Also there's a foreign key so it's easy to obtain related entities
ok
That should work ๐ค
patient = Patient.query.get(patient_id)
visits = patient.visits.filter(start_of_month <= PatientVisit <= now).all()
You can also make sql do the sum ๐
ok, im going to try it rn
im sorry, whats a "orm"?
well no
Hello, how do I convert the first word into uppercase or capitalize in php html?
PHP ๐
for example i input Web DevelopMent then the result should be WEB Development
Flask
import os
import secrets
from flask import render_template, url_for, flash, redirect, request, abort, session, jsonify
from flaskblog import app, db, bcrypt, mail
from flaskblog.forms import PatientForm, MedicineForm, RegistrationForm, LoginForm, DetailForm, AddWorkLogForm, UpdateDoctorForm, AdminLoginForm, AdminRegistrationForm, AddannouncementForm, RequestResetForm, ResetPasswordForm
from flaskblog.models import User, Detail, Medicine, Patient, Worklog, Admin, Announcement, Newpatient, Totalpatient
from flask_login import login_user, current_user, logout_user, login_required
from flask_mail import Message
from datetime import datetime```
am i in the right cahnnel?
show flaskblog.models imports?
User, Detail, Medicine, Patient, Worklog, Admin, Announcement, Newpatient, Totalpatient
these?
@coral bluff You are but it's more or less a python server ๐ I have some experience with php but don't really want to touch it
@terse vapor Just imports on top of models file
oh alright. Thanks for the information 
@coral bluff What are you using php for?
for my project
I mean what kind of
Just plain php? ๐
I wouldn't develop anything in plain php
If you want it to be manageable after it grow to like 5 files ๐
ooooh!
That's easy to do in py ๐
yeah im still learning in php and also in html ๐
I asked you to show the imports...
@coral bluff
>>> s = "Web Development"
>>> words = s.split(" ")
>>> words[0] = words[0].upper()
>>> " ".join(words)
'WEB Development'
๐ค
I would just find methods that do the same in php
I have a url pattern that looks like this:
re_path(r'var1/(?P<var1_id>[0-9]+)/edit/(?P<var2_id>[1-5]+)', view_1),
This should match var1/47/edit/3 for example. Is there a way to dynamically set the view function the URL is handed to based on the last integer (3 in this example)?
So, var1/47/edit/3 is routed to view_3 in views.py, while var1/47/edit/4 is sent to view_4
Creating multiple view usually isn't the way to go
You can pass variable with that number into view itself
Yeah, I know I can do that, I'm just concerned about a bloated view method. I though separating out the views for each number maybe cleaner.
Maybe I'm just over thnking it.
Why would you have a bloated view in a first place? ๐ค
What these last digits mean?
I'm using the digit to determine which model to edit.
So they're different models or different model instances (rows)?
they are different models
a parent model. When var1_id is created, new object for var2 is also created. model for var2 has a fk relationship with var1 model.
agree. var names posted here are just placeholders for actual variables I'm working with.
logic is same though
yes, templates
You can have 5 view that would modify their own models
That would be a good approach
re_path(r'var1/(?P<var1_id>[0-9]+)/edit/(?P<var2_id>[1-5]+)', view_1),
In this case above, all 5 possible options will be routed to view_1 method.
Then while inside view_1 check for int and send them to their respective view?
I want to cut out the intermidieta view_1 to start with.
You can have something like
path("something/<int:someting_id/edit/another-thing", edit_another_thing_view)
...
For all five of them
yeah, explicitly state the urls.
I guess that is the way to go without tripping up myself
Thanks! I'll do this.
You could also make 5 edit pages for your different entities
๐ค
At least that would be easier if you use templates
Totally!
Hey, I've got my code down to ```py
@app.route("/api/postmethod", methods=['put'])
def journal_put_controller():
req = request.get_json()
absolute_path = os.path.dirname(os.path.abspath(file))
file_path = absolute_path + "/data/journal_testfile.json"
with open(file_path, mode="a") as outfile:
json.dump(req, outfile)
return {"message": "JSON Received"}
```json
{
"journals": [
{
"date": "01/03/2021",
"name": "Test",
"note": "Testing"
},
{
"date": "07/03/2021",
"name": "Test",
"note": "Testing"
}
]
}
It should print out the text that I've given
@nimble dawn would you like the color not to be white?
or to fit it differently?
Hello, this is a web dev help question so not exactly python related, but I would like to see if anyone knows how I could get the following code:
<div class="Hamburger_menu">
<img src="{% static 'images/logo.jpeg' %}" class = "logo">
<input class="hamburger_checkbox" type="checkbox" id="hamburger_id">
<label class="hamburger_icon" for="hamburger_id">☰ </label>
<label class="hamburger_cross_icon" for="hamburger_id">โ</label>
<div class="header">
<ul>
<a>
<input class="dark_mode_button" type="checkbox" id="dark_mode_id">
<label class="dark_mode_button_display" for="dark_mode_id">DarkMode </label></a>
<a href="/logoutpage"> Logout</a>
<a href="/logoutpage"> Logout</a>
<a href="/logoutpage"> Logout</a>
<a href="/logoutpage"> Logout</a>
</ul>
</div>
<div class="news_div">
<h1>{{Article_name}}</h1>
<h1>{{Article_author}}</h1>
<h1>{{Article_title}}</h1>
<h1>{{Article_desc}}</h1>
<img src={{ Article_img }} alt={{Article_name}} class="acticle_img">
<a href= {{ Article_url }} >link text</a>
</div>
</div>
@media only screen and (max-width:600px) {
.hamburger_icon{
display: block;
}
.header{
text-align: center;
width: 100%;
display: none;
}
.header a{
display: block;
border-bottom: 1px solid red;
}
input:checked ~ .header{
display: block;
}
input:checked ~ .hamburger_cross_icon{
display: block;
}
input:checked ~ .hamburger_icon{
display: none;
}
}
/* Dark Mode Button */
/* .dark_mode_button{
display: none;
} */
input:checked ~ .a{
background: red;
}
What I am trying to do is to get the dark_mode_button to change the backround color of tag a. I'm not sure how to do this because I have already used an input tag, therefore input:checked does not work!
Any help would be appreciated!!!
I use python flask, and to make a path, normally it's this:
app.route('/path')
def path_funct():
how would i create a new one without actually editing the code (when it receives a POST request, it makes a new path)?
Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
how to fix this error
i install log4net but it still giving me error
Hey guys, how do I get this to work:
input#dark_mode_id:checked ~ #header{
background: green;
}```
```html
div class="header">
<ul>
<a>
<input class="dark_mode_button" type="checkbox" id="dark_mode_id">
<label class="dark_mode_button_display" for="dark_mode_id">DarkMode</label></a>
<a href="/logoutpage"> Logout</a>
<a href="/logoutpage"> Logout</a>
<a href="/logoutpage"> Logout</a>
<a href="/logoutpage"> Logout</a>
</ul>
</div>```
You don't usually create routes dynamically but rather matching them against some kind of pattern, say
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
(Example from https://flask.palletsprojects.com/en/1.1.x/quickstart/)
@inland oak You can automate stuff in windows too yakno ๐
treat $PROFILE as .bashrc ๐
linux is an one big IDE.
no need for Windows
like... what's the point to be in Windows
if we need to adapt our project to run in Linux anyway?
well, most regular users, including developers use windows, that'd be one major reason
web dev projects are run at Linux servers.
yea
users get their results through browsers
no need for the work to be windows compatible
but development itself is mostly done on windows devices, I'm not saying this is how it should be
but that's how it is
and there are applications that are not happening on web
a decent few in fact ๐
same can be said about Windows
you can't launch without pain there... (or just can't)
Docker (+compose)
Kubernetes
Redis / Celery
Postgres
Nginx
if you want to be python backender, which can deploy his own project
better be in Linux
launch what?
All right, easy example
for any web project, Flask, Django, or whatever
there is requirement often to be able
settings tasks in Celery
which use Redis database
how are you supposed to debug it in Windows?
I've never worked with celery so i wouldn't know
deploying docker is simple on windows
only Windows 10 supports docker
and win server
yes, we can blindly write instructions from Windows for Linux
but why to endure pain (in form of increased time to debug)
when it can be tested directly
if you are in Linux?
you're making very broad statements I'm trying to understand
why imply debugging takes more time in windows?
i wish to know
because
you have no direct/easy access to install services like Docker/Redis/and e.t.c. in literally few commands
Your dependencides only where tested to work OK in Windows
Your application paths were tested only to work OK in Windows
all it leads to...
You do know Docker on windows uses WSL right?
testing application through... some ssh connection
on Linux Server
but it is not really convinient
when it can be tested on main machine
yes, some could write piplines
and you're wrong
for automated testing for Linux compatibility
there are scripts that automate installing those
correct
and powershell is extremely powerful shell in itself
thanks to it's .NET bindings
but, we are usually needing linux scripts to automate our CI
windows scripts are next to useless
if you have linux server sure
i'd image that being the case
I mean, depends on your workload, powershell as shell is available on linux freely
so if you work with python and pip, pwsh script is "cross platform" in that sense
it can work as substitution
but it smells weird to me
ยฏ_(ใ)_/ยฏ
after all, it is not even available in any Linux
it is
without installation of it
in all of them
it's open source
oh
yea, you have to install program to use it
that's how things work yes
it's not preinstalled
๐
it will make usage of public docker images harder
why so
well, you would have to... you know...
being finding how to install powershell to every differently used docker image
and you don't for sure always, which is even Linux version is there
Ubuntu/Alpin/Debian
stable, or super freshly new ones
shell scripts work always
so you're discussing scripts inside docker images now?
I was under the impression docker images are supposed to be immutable, so majority of it's use should be with just dockerfile
running shell script directly on image seems unconventional
well, yes. But from project to project, to different goals
you are usually changing which docker image you use
because some of docker images already have everything preinstalled
in terms of going to be used services
saves a lot of time, from doing on your own
for example
docker image with preinstalled
python
or npm
or even with preinstalled docker inside of it
continue the list with any required service
yes, what about it?
forget about it
Hello, does anyone know the HTML language here? If anyone knows, the link does not work when adding the link, if you know why can you write please, thanks
I am trying to run django in production mode, but for some reason I am getting a 500 error
@manic current https://www.w3schools.com/tags/att_a_href.asp
href attribute is http reference (aka link)
Okey thanks :)
try with flags
runserver --noreload --insecure
you have probably static file problem
this is bad solution to test it
still the same error
nothing was outputted on my console
[26/Apr/2021 10:54:14] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 1451
If I wanted to like keep track of a list that each indivdual user has inside of Django, how would I go about doing so
if there a video someone has
or how I would do it
hey can someone please help me with my HTML coding please
do you have multiple
try:
pass
except:
pass
try:
pass
except Exception:
pass
which aren't having specific error mentioned?
do they catch just except or general error Exception?
no I dont
@hard quail list as a python list? more commonly you'd use a database if you need to store some data permanently
if you were discussing a "list" on client side that will only hold objects temporary, you would likely have to use JS for that
"Django" as framework doesn't hold data, whatever database you use does (likely SQLite)
hm ok I will look into it
would it be hard
to store data
i.e jimmy has 5 appels
and 10 bananas
I have a chat exported in file.txt I'm turning this into csv file by pandas and plotting some graphs with that csv file
Someone tell me how do I start implementing this in django
I have to put it on the web please help
Classes can be split so they has to
I don't know about django much but I know classes
ask others they might help you better
I know, how that supposed to work with classes
I just not sure how it would interpret django
web scrapping
with beautiful soup or xpath
which framework can I use for sql database in aiogram(python)? I want something like in django
which framework can I use for sql database in framework aiogram? you said rubbish
you probably meant to say, which ORM library I could use in framework aiogram
the answer: SQLAlchemy, peewee, PonyORM
I checked it, I think it's better to use django, how to use django with aiogram?
Can i make comment section in my website using python?
yes
Can you teach me?
Like when a user comments in it , it should be displayed on the website
Something like that
I just want to learn that
u can use the post id on comment model
@terse vapor dm?
sure
I have a question concern an error I encounter, what's the appropriate channel to drop that please
any recommendations for this? Access to fetch at 'http://URL:8000/search?number1=2C5Z-6A666-AA&name1=&number2=&name2=&number3=&name3=&number4=&name4=&number5=&name5=' from origin 'http://URL:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. i can successfully do my search on my main computer but on another i cant.
here is good (if it's related to web development)
using django?
Okay. Great. I will shortly. Thanks
Hi.
I'm back again :weary: :weary:
Error everywhere.
I am working on a project using Django, and unfortunately my python version doesn't allow me to install django-filter.
I had to uninstall the already version (3.9) to a lower version (3.7). And now I'm unable to install Django on this new version, not to talk of continue my project anymore.
Any help will be appreciated pease. Thanks house.
did you setup CORS headers?
i did not. it is working on one machine which is weird to me.
django-filter support python 3.9?
well, you should - if you're making any requests from your frontend (given that it's a different origin from your backend, and if it's running on another port - it will be) you have to setup cors.
It doesn't
okay ill look into this. it is working on a different machine from the origin. its running off of a VPS
press the link on pypi, it does
Is this recently updated?
Because, I still checked yesterday and discovered it's not supported on version 3.9
Yeah. I just did and I see that it do supports it. The screenshot I shared above was taken in my research yesterday
apart from that I would just say reset your virtual environment & reinstall dependancies
I'm even more confused now, because I uninstalled the version 3.9 and installed 3.7 already. Now I'm unable to install Django less proceed on my work ๐ฉ ๐คฆ
I don't seem to understand this. Could you provide a resource to walk me through on how to please
Any idea?
guys do someone knows why selenium doesnt really work if you dont look at it (if i dont scoll down manually it doesnt work)
im getting it to work while on incognito on the work computer. any thoughts on that?
but not on a normal browser
ill try and clear cookies etc. but im confused lol
that did it i guess
your browser may have CORS turned off - I don't know, but if you do not implement CORS your frontend will not be able to communicate with your backend given that they are on different ports.
well they arent currently running on different ports. is that the best practice for running react + django is to serve them separately? im currently having django point to the react html and running it that way.
I don't know much in terms of deployment. I am moving towards SSR w/ django/react with next.js
alright gotcha. ill do more research into that. im kind of just trying to learn everything there is and just getting through my first small project on web dev so
thanks ๐
Does anyone know how to get live reload to work for Jinja templates? I have debug mode enabled. if I make a Python change, then it automatically reload. I am unable to get it working for Jinja templates. I know I can do the refresh myself, but I really need live reload
do I really need django-celery-beats, and results?
you can set up periodic tasks without them I believe, just using django-celery
in celery settings you can specify the tasks you want on the beat
then run a beat / worker
Django-celery-beats, results is just django backed ORM, but if I setup simple without them. Where will it save?
$10 Bitcoin if anyone can figure this out for me.
I have tried:
python-livereload - works but crashes when I change a .py file
TEMPLATE_AUTO_RELOAD doesn't work since Flask 0.1
jinja_env.cache = {} - not working
There is a way that I can do on my site (html, css, js) login with google gmail?
Anyone has a good javascript tutorial?
server = Server(app.wsgi_app)
# server.watch
server.serve()```
Hello, i use Flask-Discord to create a connection but Firefox return me after accept the connection Firefox canโt establish a connection to the server at 127.0.0.1:50000.
@app.route('/login/')
def login():
if not discord.authorized:
return discord.create_session()
if discord.authorized:
return redirect(url_for('dashboard'))
@app.route('/callback/')
def callback():
data = discord.callback()
redirect_to = data.get('redirect', '/')
return redirect(redirect_to)
Any idea?
Hello! I just read about race conditions and how to solve them in Django using the F function.
However, since I could not summon a race condition by myself, I am not sure if I solved it right. Can someone help me check my code if I solved it properly?
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes = F('votes') + 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
you sure your port is 50000 and not5000
Patient = Patient.query.first()
for i in Patient:
if i.name not in i:
a = Totalpatient()
a.count += 1
db.session.add(a)
else:
a.count += 0 ```
Why is this TypeError: argument of type 'Patient' is not iterable
maybe because the model is also called Patient ?
maybe try a = Patient.query as a test
u mean the Totalpatient model?
then try print (type(patient))
ok
and i don't know, if your Totalpatient model is called that, it should be Patient = Totalpatient.query
well, patient is about patient personal info, and totalpatient is just counter
try what i suggested first, I think that could be the issue
the type is a list
you have a class called Patient and you also have a variable called Patient
change the variable to smething else, it could be trying to loop through the class
ya, but im just using the loop to go over everything inside the model
to check if the new input exist in the db
Yes I understand that. But how is the code supposed to know if you're looping through a class or a variable ? Have you tried to change the variable name ?
ask your questions
k
forms.py
https://paste.pythondiscord.com/inocixused.py
flaskblog.py
https://paste.pythondiscord.com/uhuhabogeg.coffeescript
register.html
https://paste.pythondiscord.com/melomicaci.xml
layout.html
https://paste.pythondiscord.com/kemoxayano.xml
The warning message in DataRequired(message='Username is required') from forms.py is not working. I mean it does not show up when I click submit and leave the form blank. Can someone explain why? I am using flask and wtf forms Thanks
try putting it before the length validator
I will try
class RegistrationForm(FlaskForm):
username = StringField('Username',validators=
[
DataRequired(message='Username is required'),
Length(min=1, max=25)
])
I did what you said. It made no difference
I'm not familiar with forms in flask, but are you sure your jinja template is correct?
{%for error_msg in form.username.error%}
sure it's not form.username.errors ? do you actually need to loop over this?
I tried both ways
the loop and non looping method in jinja2
i can try errors
instead of error
Give me a sec
It made no difference changing the code to errors
Should I try reddit flask
can't help you without a minimum working example then
I'm not familiar with the forms
I'll pass ๐
Hello
I'm looking for some help on data filtering for SQLAlchemy
I am designing REST APIs with FastAPI framework and I am looking for some way to filter objects in db in ascending/descending order. Unfortunately I couldn't find anything on https://fastapi.tiangolo.com/tutorial/sql-databases/. The only query method I know is db.query(models.User).filter(models.User.id == user_id).first() . anyone knows other queries and any documentation to follow?
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Thank you~
does anyone know how to input a number with selenium in this field?
<input name="dob-month" class="step__input--date--mm" type="number" placeholder="mm" min="1" max="12" data-maxlength="2" value="" autocomplete="bday-month">
use .sendkeys on element
it says its not interactable
^ most likely
looking for help with data-mining a website using python... I wrote a script a few years ago that worked and now doesn't and I'm not an html expert so I'm a bit lost... if someone is interested in helping, please DM me... I just had a few questions. Thanks!
how do i have an image and make a link for it?
i have the image as a file on my computer
i use python flask
i don't know how to put the image in the path though
check its path like c users this pc download
it would like this
how can I make routines in a Django.
like if you want to send emails or update the database after a uniform interval.
Celery + Redis
or just daemonized thread in background, if we aren't going for overkill
can you elaborate...
or point to an example...
I have one, but is not is not having clean code yet
if you wish to get clear code, you'll have to wait a bit
I thought to make it clean today
otherwise, you are welcome to see not clean code too ;b
Thanks.
for now I'll be using django-apscheduler
but I'd love to see you work too...
how to activate a virtual env
C:\User\source\venv name\Scripts\activate.bat
thanks ๐
i am learning flask
Hello, can i put a question about graphql here?
guys in XSD why there is an attribute called schematypens
and not schematypes , like what does n stands for ?
you don't need to advertise that everywhere, is someone knows and can help you out, they will surely help you ๐
if you think the question is not suite for a single topical channel, you can use the help channels, see #โ๏ฝhow-to-get-help
oh ok 
Can anyone help me how to feed an custom zoho crm module through Djnago models.Manager ?
**NB : I'm able to feed or insert data to zoho Contacts module easily ,but not my custom deposit module
Thanks in advance ๐
what are some good starter projects for a profile on freelancing site?
Okay I have a question.
I have a figure tag, inside which there is an img tag. What I want is that I wanna show a popup when the image is clicked.
Maybe you have to create a function for it
Yeah, I figured it out. Thanksies!
anyone here flask user ??
yeah, many here do use flask, go ahead and ask your question
I have a question about Django REST Framework although it is more of a web-dev design question I think.
If I make an API using DRF what do I then do if I want to have a nice front-end that can be used for actions too?
i.e. I make a DRF API which allows CRUD operations and returns JSON data.
I now want to have nice html forms for some create/update actions and say a dashboard page which displays some tables/graphs using the data in the DB
Do I make parallel views which would presumably be very similar to some of the api endpoints for the forms?
same question I wonder
usually companies use React for a front
But I am not ready to learn react yet,
so I'll try to make it fully from Django
perhaps JQuery could be what I need in order to do it nice
Hello there I am new to flask and python and I am trying create a very simple flask api with json data, and this is my code.
@app.route("/data/<string:alpha_code>", methods=["GET"])
def about(alpha_code):
response = None
with open(os.path.join("data.json"), "r") as jsonfile:
file_data = json.loads(jsonfile.read())
json_data = json.dumps(file_data)
for item in json_data:
for key, value in item.dict().items():
print(key, value)
return response
And this is my data (list of dicts)
[
{
"alpha_code":"US",
"country":"United States",
"domain":"acu.edu",
"name":"Abilene Christian University",
"web_page":"http://www.acu.edu/"
}
]
# multiple dicts
And I am getting an error : AttributeError: 'str' object has no attribute 'items'
Please can anyone help me with this ??
How can I open my website on mobile
I don't know a first thing abouth flask but it looks like you're trying to open file in reading mod and then write your json to it.
[Q] FLASK + database:
I can retrieve successfully some data from database and show it in html document. However, in my database I have a field with TEXT, and there is a line like "Hello \nWorld \t". Problem is that it shows in html data without these new lines and tabulators. And I need them to show certain description with those new lines, new paragraphs etc. How to do it in html jinja2?
Example:
- Data in database:
("Vit C", "\tVery Healthy\nIt is important for immune system\n") - HTML jinja:
{{ data[1]|safe }} - Result:
Very Healthy It is importnant for immune system
EXPECTED:
Very Healthy
It is important for immune system
P.S: Funny thing is that in INSPECT ELEMENT mode, description is printed correctly, however in my html you cannot see these new lines, tabulators etc. wow?
Django models.CharField has uselss __doc__
is it possible to override it?
self.__doc__ = str(self.field.__repr__())
with something that has better __repr__ inside of it
anyone mind help me check why the message from contact form didnt send to email?
https://github.com/GervinFung/My-First-Web/blob/test_phase/php/contact.php
for item in json_data.items():
for key, value in item:
print(key, value)
With DRF you create API views. When a request hits the endpoint, it is routed to that view. So you can create a seperate frontend (say, in React) and send a request to your API view which will then return JSON data - which your frontend can consume.
Sorry if i am interjecting...
Is it OK to default to using
SECRET_KEY = getenv("SECRET_KEY",'<redacted>')
for production use? Asking with respect to Django. And are there any other methods to keep the SECRET_KEY out of VCS?
super secure choice
import secrets
SECRET_KEY = os.environ.get("SECRET_KEY") or secrets.token_hex(32)
generates random secret key every time you start your application)
unless you specified one in environment
Can I use this for any and all projects or is this suited to only specific situations ?
shrugs
it works for everything
but in some situations you would need somehow to specify
that you have the same SECRET_KEY in deployment
and not everytime changing
would that invalidate CSRF tokens that were set before your server restarted? with an old secret key?
mm, highly probably yes.
Incase the environment variable is set then no
you can specify stable key from env anyway
then it would not be a problem
Thank you @inland oak !
So I have to use a JS framework. Is there a way to do the same just using Django? I really can't be arsed with learning JS for a personal project haha
You don't need to use a JS framework, but it's recommended. Using plain HTML you can create a form which sends a POST request to your API view, but you're pretty limited without JS
Limited in what way?
Would you not do something like call the DRF endpoint from within a regular django view?
e.g. you don't have any access to JS libraries, you can't change DOM in an efficient way. You don't have as much control
Right. But why do you need that is my question I guess
you can make a request to your endpoint, sure, but I don't see why you would do that from another view
Hello there I am getting a key error in flask. Basically I sending a patch request with optional arguments.
code :
if request.method == "PATCH":
request_data = request.get_json()
# alpha_code = request_data["alpha_code"]
# country = request_data["country"]
# domain = request_data["domain"]
# name = request_data["name"]
# web_page = request_data["web_page"]
response = None
with open(os.path.join("data.json"), "r") as jsonfile:
universities = json.loads(jsonfile.read())
for university in range(len(universities)):
if universities[university]["name"].replace(" ", "").lower() == university_name.replace(" ", "").lower():
response = universities[university]
# if request_data["alpha_code"]:
response["alpha_code"] = request_data["alpha_code"]
# if request_data["country"]:
response["country"] = request_data["country"]
# if request_data["domain"]:
response["domain"] = request_data["domain"]
# if request_data["name"]:
response["name"] = request_data["name"]
# if request_data["web_page"]:
response["web_page"] = request_data["web_page"]
return jsonify(response)
Python is giving me this error = response["alpha_code"] = request_data["alpha_code"]
KeyError: 'alpha_code'
Basically saying this key doesnt exist. Since I am not sending it from front end
{
"country":"TEST"
}```
How can I make it accept optional request params ??
@opaque rivet
Perhaps I'm not explaining very well. In my head I would have endpoints like so:
POST api/tasks :creates a task
mysite.com/tasks - GET lists tasks
mysite.com/tasks/create - GET displays form, POST submits form and then redirects back to mysite.com/tasks on success
And basically the stuff at mysite.com/tasks seems like it's largely just replicating the api behaviour no? So I was wondering if there is a good way to leverage that
Yeah I'm not fully understanding what the question here. They're all valid API endpoints (with the exception of mysite.com/tasks/create). There really isn't anything different than a standard view or an API endpoint, it's just that your API endpoints are should be RESTful: https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/
a try catch is the most basic sol. use if if you know when each param will be sent
If you don't plan on having a seperate frontend, or do not plan on making individual requests from your frontend, just use views
Okay will try that thanks
What do you mean by "making individual requests"?
I'd like to be able to POST a JSON to /api/tasks OR to fill in an HTML form which would create an object
Literally, making a request from your frontend if you want to retrieve data to display (usually in an AJAX fashion)
sure, so what is the question?
POST api/tasks :creates a task
mysite.com/tasks - GET lists tasks
These 2 can be APIs, the other one is a view
I guess my question was how would you get the form page\
I could use a modelform with Django for example to generate an html form which had all the right fields
I really don't want to have to write any JS
So you want to show a form with pre-filled fields?
Erm, for an update I guess?
But if you're navigating to a page to create a new task it wouldn't be pre-filled
It would just have empty fields right
Yeah so your question "how would you get the form page" would just be rendering a template with a form and on submission making an API request to your endpoint
Ok. And that is an acceptable way of doing things?
What is API
yep!
<form method="post" action="your_endpoint">...</form>
Ah but now that endpoint would just return JSON...
yep - API endpoints should only be returning that anyways.
But if someone is submitting a form in the browser they don't want to get JSON back haha
well yeah - and that's why I said that APIs are meant for separate front-ends. To be honest this all can just be written in one view, or if you really want to opt for another endpoint, just get that endpoint to save whatever in the DB then have you view reroute your user once the form is submitted.
Honestly maybe I am overthinking this
Perhaps it is acceptable to basically have the behaviour of some of the endpoints under mysite.com/api/tasks replicated by the views serving the html pages at mysite.com/tasks?
I just thought that since that would mean there were two separate means of performing CRUD operations then it would be incorrect
Yes, just replicate it within the views. It's not a bad thing that one view can handle both GET, POST, etc.
Does anyone know how to create a paginated API in flask ??
how to transfer a sqlalchemy row(e.g. name) into a list in flask?
Hey @whole kayak!
It looks like you tried to attach file type(s) that we do not allow (.xml). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
lol
welp to paste bin ai go
i get this (https://pastebin.com/du7fFEw7) as a api output
as you can see it is xml but when i pipe it into ET.fromstring(f'{xml.read()}') (xml is a output from os.popen which i use to query the api)
but i get this error Traceback (most recent call last): File "C:\Users\walke\OneDrive\Desktop\trash nation states bot\bot.py", line 24, in <module> print(NS.getIssues('password','walksanator','useragent')) File "C:\Users\walke\OneDrive\Desktop\trash nation states bot\bot.py", line 21, in getIssues xmlo = ET.fromstring(f'{xml.read()}') File "C:\Program Files\Python39\lib\xml\etree\ElementTree.py", line 1348, in XML return parser.close() xml.etree.ElementTree.ParseError: no element found: line 1, column 0
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
def getIssues(password,nation,userAgent):
xml = os.popen(f'powershell -Command .\\TopIssue.ps1 "{password}" "{userAgent}" "{nation}"')
print(xml.read())
xmlo = ET.fromstring(f'{xml.read()}')
return(xmlo)```
here is the function
and here is the powershell script (incase you need it)
$url = "https://www.nationstates.net/cgi-bin/api.cgi?nation=" + $args[2] + "&q=issues"
$xml = curl -Headers @{"X-Password" = $args[0]} -UserAgent $args[1] $url -UseBasicParsing
[xml]$pxml = $xml.Content
[xml]$a = $pxml.nation.issues.OuterXml
echo $a.innerXml```
(i am working on a discord bot to play nation states)
if i can get this to parse right
any idea why ET is unable to parse it
Is it possible to paginate json data (locally stored in a .json file) in Flask ? I am looking online and every tutorial is using a built paginate() from the database ORM. Can anyone explain the entire concept of paginated API in a nutshell ?
can some one explain me what does this module dou py import parse_qs and what does this mean ```py
index = parse_qs(self.path[3:])['index'][0]
google it
Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.
The optional argument keep_blank_values is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.
The optional argument strict_parsing is a flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.
The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method.
The optional argument max_num_fields is the maximum number of fields to read. If set, then throws a ValueError if there are more than max_num_fields fields read.
The optional argument separator is the symbol to use for separating the query arguments. It defaults to &.
Use the urllib.parse.urlencode() function (with the doseq parameter set to True) to convert such dictionaries into query strings.
Changed in version 3.2: Add encoding and errors parameters.
Changed in version 3.8: Added max_num_fields parameter.
Changed in version 3.9.2: Added separator parameter with the default value of &. Python versions earlier than Python 3.9.2 allowed using both ; and & as query parameter separator. This has been changed to allow only a single separator key, with & as the default separator.```
Does anyone know how I can make a bot dashboard ?
Are there any good tutorials using Flask ?
@whole kayak but i dont undesrtand the parth with numbers self.path 3: index 0 what should that mean
first part returns a slice of a list
from 4th index to last
['index'][0] this accesses the element index in the list and [0] accesses the 0th element of the index
How can someone tell if a website would stop/prevent you from web scrapping?
Depends what you want. But I like Streamlit for a quick, sexy dashboard. For anything more technical / custom, check out Plotly
I found this vid really useful for grasping Streamlit. https://www.youtube.com/watch?v=0ESc1bh3eIg
In this video, we build a multi-functional dashboard using Streamlit. We display Tweets about stocks from popular traders on Twitter, display all mentions of a stock symbol on StockTwits, create a simple screener for technical patterns, display a Plotly candlestick chart, count recent mentions of stocks on WallStreetBets.
What's everyone's favourite free wireframing app?
Are there cases where a company would be ok if someone web scrapped them?
We work with a company. We asked them for some data. They asked us for our FTP credentials, so they can give us that data. We dont have an FTP server, so I was thinking of web scrapping their website. But I know companies dont like it when someone web scraps their website.
Problem is they would have our ip address and we have to login to see that data. So when I create a web crawler they would know it's us.
Web scrapping/crawling
for i in db.session.query(Patient.name).all():
mylist1 = list(dict.fromkeys(i))```
why does this for loop function only shows one name?
does anyone know if there would be a way to get around a max amount of responses from this request? https://stores.boldapps.net/front-end/get_surrounding_stores.php?shop=meat-church.myshopify.com&latitude=27.6445079&longitude=-80.4048306&max_distance=0&limit=1000000&calc_distance=1 i am needing to get all of the results they have. if not ill just end up picking random locations that captures at least most, but not all of them basically i guess.
it looks like it is capped at 1000
nvm, i solved it
there must be some sort of pagination or offset, that would show you the next 1000 results
not sure how to even try to do that tbh. i tried changing the limit in the URL and it only works up to 1000
i know i could get a rough list by picking out different lat/long and going around the map and getting most and getting rid of duplicates but im trying to learn if there is a better way of doing it through the API
If an api has a max limit of how many items it returns per request, then you cant exceed that.
alright thanks. looks like rough list it is
Yeah, this is the part where if a company has good documentation, it's fun. But if they have bad documentation, you just have to do a lot of exploration on your own.
If they are happy to send you the data, I can imagine they'd be happy for you to scrape the data. If you can otherwise have access to it (by logging in), I think web scraping should be fine. The issue comes when you're spamming their server with requests. If you're doing that, that's going to piss them off. But anyway, I'd simply ask them for permission to scrape the data.
I did this repo , but I am stuck at how sqlite < celery > redis work https://github.com/SkyBulk/celery
Are widgets and css applied to a model/fields in forms.py (ModelForm) reapplied to those fields when a form is redisplayed after failure?
Form displays well when methods is GET.
But not after POST failure.
https://python-forum.io/Thread-problems-with-flask-and-celery
made a post on the python forums if anyone here knows whats up
hey.. how did you make to setup properly celery with redis as message broker?
what exactly is the job of a devops person?
managing aws/firebase and deployment stuff?
devops is built around the idea that software development and deployment should be frequent, efficient, and automated.
so basically building a good pipeline
ahh i see. also what does "pipeline" exactly mean?
ideally, when you want to deploy, it should take just one command
and that will run all your tests
take care of any infrastructure setup
notifications
monitoring
etc.
thatโs the pipeline.
ahh that makes more sense, thank you
ooo that seems like a handy gif to bookmark
To be automated as possible
To run every hour
Or even to run completely automated every minute, by trigger from submitted commit (in master branch for example?)
I have automated deploy script
In gitlab
That builds my sphinx documentation
And puts to gitlab pages
lets say if there wasn't anything new being changed, would the automation still go through?
And checkers, which run unit tests, lint checkers, build/dependency checkers
for the automation scripts you use cron jobs?
Github/Gitlab pipline runners
Online and self hosted
Those I already used
Systems like TravisCi, circle ci
ohhh, so it checks for commits to your master branch, thats when the automation takes place
Basically yeah.
Commit is submitted
Triggers job tasks and puts to queue
Runner checks available jobs and runs them as soon as possible (often in parallel if possible)
Deploy to production is usually separated, to be triggered manually
Deploy to test server can be fully automated
ahh i see. this clarifies it for me a lot more. thank you
im gonna try it out and set it all up for one of my projects
Useful for code reviews
would you recommend gitlab or github for this
They are equally good, in my opinion
I liked gitlab slightly more, may be
interesting. I'll play around with both
Usually gitlhub/gitlab pipelines have no limits only for public repos
Or if you setup self hosted runner on your own server
I installed gitlab runner on mine, that was easy. Quickly integrated with my online repos, removed time limits for private pipelines
One self hosted runner can satisfy needs for a lot of private repos.
one runner can run jobs in multiple parallelism + queue
ah i see. thank you for all this info btw, really useful
U a welcome.
Btw, besides those things...
Devops should be good with docker/docker compose
Deploying with Ansible at the moment popular.
Most popular question to devops, if can they answer next question
Can someone recommend a great solution to hosting a FastAPI on multiple servers so the load can be balanced and if one goes down the other can still handle the requests?
This can be possible with Kubernetes for example
oh. Yeah I have heard about Docker but haven't looked much into it. I'll research more about Docker.
@app.route("/home-for/<string:name>", methods=['POST', 'GET'])
@login_required
def doctor_information(name):
current_time = datetime.now()
time = timedelta(weeks = 4)
four_weeks_ago = current_time - time
filter_by_month = db.session.query(Patient.name).filter(Patient.create > four_weeks_ago).all()```
It seems like my code will restart the counter(4 weeks) every time I refresh the page, so is there any way to prevent this happen?
what do you want to happen?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="clock.css">
<title>digital clock</title>
</head>
<body>
<section>
<div class="clock">
<div class="container">
<h2 id="hour">00</h2>
<h2 class="dot">:</h2>
<h2 id="minute">00</h2>
<h2 class="dot">:</h2>
<h2 id="seconds">00</h2>
<span id="ampm">AM</span>
</div>
</div>
</section>
<script>
function clock(){
let hour = document.getElmentbyId('hour');
let minute = document.getElmentbyId('minute');
let seconds = document.getElmentbyId('second');
let ampm = document.getElmentbyId('ampm');
let h = new Date().gethours();
let m = new Date().getminutes();
let s = new Date().getseconds();
var am = 'AM';
if (h > 12){
h = h - 12;
}
hour.innerHTML = h;
minute.innerHTML = m;
second.innerHTML = s;
}
var interval = setInterval(clock, 1000);
</script>
</body>
</html>
i am making a clock
i dont know why it is not working
it is only showing 00
can anyone pls help with django project structure
only the structure
I want to add tornado to my project, but where would I place it
the handlers and all those stuff
i found the error
anyone familiar with html and css in here
Hi all - Iโve been building ImagineAI, a free low code platform aimed at engineers - basically, you would simply specify your backend project spec in our UI andย we instantly generate high quality, production-ready source code, including 100% unit test coverage, based on the spec (we are initially supporting Django and Node). We have no lock-in, so you can download the source code and customize as you wish.
This way you can save time on writing boilerplate code for things like ORM, APIs (in Rest or GraphQL), Auth etc and can focus on writing custom business logic.
We are releasing a closed beta version of this tool in mid-May. Are there any backend / full stack product engineers here who would be interested in this? If yes, Iโd love to connect here via DM or via anusheel@imagine.ai, and can include you in our our beta release!
can someone help me regarding .net problem
i get this error when i open my page i am using crystal report
at HTMLImageElement.<anonymous> (CivilWorkSummaryUniWise.aspx:201)
at HTMLImageElement.dispatch (jquery2.js:5)
at HTMLImageElement.v.handle (jquery2.js:5)```
at CivilWorkSummaryUniWise.aspx:646```
just make it an app
start a new app for this particular tornado feature
python manage.py startapp tornadoapp
Could someone help me why my background color won't change?
I've tried this:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Furniture Inventory</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
<style>body{background-color: gray !important;}</style>
</head>
<body>
....
I want my body's background-color to be gray, but that doesn't happen even with the !important thing
So, what am I doing wrong? (I'm using AdminLTE and Bootstrap btw but yes I want to override the background color regardless)
maybe try to put in .css file then link rel stylesheet etc and maybe it will override more efficient
@pseudo marsh
[Q] FLASK + database:
I can retrieve successfully some data from database and show it in html document. However, in my database I have a field with TEXT, and there is a line like "Hello \nWorld \t". Problem is that it shows in html data without these new lines and tabulators. And I need them to show certain description with those new lines, new paragraphs etc. How to do it in html jinja2?
Example:
-
Data in database:
("Vit C", "\tVery Healthy\nIt is important for immune system\n") -
HTML jinja:
{{ data[1]|safe }} -
Result:
Very Healthy It is importnant for immune system
EXPECTED:
Very Healthy
It is important for immune system
P.S: In INSPECT ELEMENT mode I can see that text is printed as it supposed to be (so new lines and tabulators appears), but in html its not displayed properly. wow?
\t and \n symbols are safe, so you should probably sanitize your string before saving it into your database or after retrieving it from db
e.g. replacing \t and \n with spaces
dear all,
good day,
i learn python langauge but i need to make web application using python anybody can suggest or help me for making this web aap...?
@cloud bone Again, it depends on what kind of web app you want to build
I'm having a great time with streamlit to avoid html, css, routing etc. https://streamlit.io/
Thank you for your response โฆ! I want to make like spend income tracker and organization like a bank details and user management...!
I would use Django if you want to render things on server side or FastAPI for api's
Streamlit is very lightweight, so depending on the complexity of your application I would perhaps go for Django
Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science.
Not quite the use case
FastAPI still can render Jinja templates but Django would be easier to pick up ๐ค
ok so i need to learn now django fremwork for building my web aap.?
Yes, but it depends ๐ค
As i said FastAPI would be better for api's
You would have to learn one of them anyway
according to my research django is famous fremwork.
This is also good but django is most famous and can find more tutorials. Thank you for recommendation.
@terse vapor has to be stored in a global variable (it will reset if the server resets)
itโs also rather outdated
if you want to do stuff like SSEs or async DB access you might have problems
shrugs
and in certain specific cases its ORM is lacking
i have made a clock using css and js
now i want to add a timer function in it
i want to create a button that will change the clock to timer
how can i do taht
that
Django channels has a function to run queries asynchronously plus better async support might come in new releases ๐ค
What uri paths should i use if i want to identify entity by two fields?
Say id and slug
Flask is simple and an easy library for web apps.
Anyone know how to create an AD authentication page with flask without a database being needed?
You can't really do auth without storing user info
Somewhere
Also i don't see a reason to use flask anymore
FastAPI is superior ๐
I guess Iโll have to use a Php connect method before being able to show the flask app.
Wdym by "php connect"
FastAPI is relatively new, the community is small compared to other frameworks, and regardless of its detailed documentation, there is very little external educational materials.
Documentation is really enough
You can use same tools you use with Flask
Php can carry out auth just from a bind no dB needed
Plus flask is much smaller compared to FastAPI
Wdym "no db needed"
How would you store user info
No database needed it just uses a lookup account and passes the authentication.
You donโt need to, it just an auth page Iโm after so only certain access group can view it
Just where
So basically another server...
if any one can give me a help
title shouldn't be null
The AD domain/LDAP server is seperate yes sorry, so authentication with the local sever in order to say yes or no to that person accessing the flask app.
Why won't you just authenticate them in flask?
So you would have more control over the process
Also making another php app seems like a bad design choice
@serene prawn https://soshace.com/integrate-ldap-authentication-with-flask/ so based on permissions it will or wonโt launch the app based on user group.
i thing that the problem is here
For API
Django can work great with plugin Django REST framework
DRF is really bad imo
Imo yes
Shrugs. Good to know.
I will still prefer django though
Because it can work as not API too
May be later, fast api then
Admin interface is awesome ;b
Save a time to make tool for moderators in almost zero time
You don't usually use admin interface in production though
But admin is good
It's not a killer feature whatsoever
DRF has interface too...
With self forming documentation
(Not really good solution though, better to add Sphinx for documentation)
FastAPI is based on OpenAPI
And drf docs are quite hard to make if you create any custom responses ๐
In fastapi you can just specify response model and that's it ๐ค
Also custom input models ๐
All right, giving up.
Fast API is cooler
๐
Hi all! Can I ask here a question about Django? I didn't found specific channel on this
Sure do
Thanks. I'm Linux user, Ubuntu 20.10. When I want create a Media_root path, I have not the path that almost all site show, I mean os.path.join...but BASE_DIR / 'directory'. I don't know how to convert the code for selecting a specific folder, outside from project (what usually is writes like: os.path.join(os.path.dirname(BASE_DIR), 'directory'.
Maybe something can help me solve this stupid problem? (I hope I explain good, English is not my native language)
https://docs.djangoproject.com/en/3.2/ref/settings/#media-root
MEDIA_ROOT should be a absolute path, you can try to use pathlib.Path and create Path object for directory you want
also you should be able to just spcify the string, like "/var/www/example.com/media/" as in docs
Thanks for the help @serene prawn
any free hosting services? (asking for a friend)
When the day pass, the for example, I add 2 patient in April 27, and the new patient in 27 should be 2, then, when it comes to April 28, it resets to 0 and starts to count again
All this fastAPI talk... but in terms of corporate / jobs it is nowhere near the scale of django/flask.
But you can't deny that it's superior to flask ๐
pythonanywhere? or Gcloud https://realpython.com/python-web-applications/
sounds like a task for cronjobs/celery
I also tried: foreign_keys=['users.uuid', 'profile.id'] and db.foreign_keys=['users.uuid', 'profile.id']
Does someone of you have informations about falcon+restful api's in python?
can some one explain me what parse qs does in simple words
Hello channel! Does anyone have experience serving React production build via Django?
I'm currently getting MIME type issues . wondering if anyone else has overcame this error
Here is some more detail about my problem if you are looking for more info: https://stackoverflow.com/questions/67271401/how-to-correctly-serve-my-react-production-build-through-django-currently-havin
I don't know if this answers your question exactly, but I think if you're using a heavy frontend framework like React, you would probably want to use the Django REST Framework.
you want to know how to use react with django?
I Have a question. do you store results in redis or postgresql for a task queue ? do I need to use the django extensions?
django itself has models
Hey i have a super quick flask-related question
true
return send_from_directory(file_path.split('/')[0], file_path.split('/')[1], mimetype="application/octet-stream", as_attachment=True, attachment_filename="grabber.exe", cache_timeout=0)
i'm trying to send an .exe file
to the client
i used to use flask
it works, but when I open it on my pc, it says "Windows can't run this app"
dont remember
What's a better alternative
i dont need to store tasks results, task scheduler on postgresql. I want to use redis
redis is just a key-value DB. What are you trying to do?
where you store your task results is up to you, I myself haven't used it, so I'd appreciate if you let me know what you're using it for ๐ I don't really see the use case
can python be used to make websites
im new so i want to know
i sorta wanted to get into python since it looked so cool and easy compared to other languages and i wanted to know if it can be used to make stuff like websites
Yes, it can, although you will need to know html/ccs at minimum, and probably use some Javascript.
Is there a current preferred user login/auth library for Flask? The login example in the tutorial seems very basic, but I suppose it may be enough
Hi everyone. I've come across a potential project where I will have to make a request to an API, get data back in JSON, format it, and generate some graphs from it. I am thinking of using Django for the backend and React.js and Chart.js for the front end. Has anyone ever used these in tandem with eachother for a similar project? If so, I'd like to chat and get some opinions.
yep - I'm currently using django as an API w/ React using apexcharts. If you want some good financial charts, use fusiontime. I would use them but I'm using next.js / SSR and they're clientside libraries so it's a pain
Django would work more than fine. You can build custom serializers (just with dictionaries) or if you're thinking you'll be doing more than a couple endpoints with more technical features I would recommend DRF (django rest framework). It's extremely powerful when used the way intended.
Thanks! Do you know of any tutorials that walk through how to integrate django and react? I know django basics but this will be my first venture using React
also thank you as well, @opaque rivet
If you haven't used React at all before I would recommend starting with that. Try making a list that you can add items to within state. I also recommend going straight for React hooks as it's easier than trying to understand classes as a beginner.
Try making a basic form that can submit data to the back end (don't do anything crazy yet).
For react the official docs is a good place to start: https://reactjs.org/
Other places are YouTube, and then look for high rated guides for both react/django together. Also for DRF go with the official docs as well.
I still dont understand correctly the workflow of celery - redis - postgresql , but I did an example of this simple crawling process in order to understand it in a better way , but #response means what I got stored in redis database https://github.com/SkyBulk/celery/blob/main/project/orders/tasks.py . what does exactly redis store as a message broker?
in this examples people use AMQP ,and redis or AMQP and postgresql, etc
https://github.com/celery/celery/blob/master/examples/django/proj/settings.py#L10-L15
https://github.com/Parisson/TimeSide/blob/master/app/settings.py#L241-L244
https://github.com/MacroConnections/DIVE-backend/blob/master/config.py#L83-L84
Distributed Task Queue (development branch). Contribute to celery/celery development by creating an account on GitHub.
ok, i will try
Other than Heroku, are there any services where I can easily deploy a Flask web application?