#web-development
2 messages · Page 221 of 1
*args allows you to do is take in more arguments than the number of formal arguments that you previously defined
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'Django')
output
Hello
Welcome
to
Django
print("django is cool")
async def test(pep_):
pep = f'{pep_:04}'
ssl_context = create_default_context(cafile=where())
conn = TCPConnector(ssl=ssl_context)
async with ClientSession(connector=conn) as session:
async with session.get(f'https://peps.python.org/pep-{pep}/') as response:
soup = bs(await response.text(), 'lxml')
even = [i.text for i in soup.find_all(class_='field-even')]
odd = [i.text for i in soup.find_all(class_='field-odd')]
even = dict(zip(even[::2], even[1::2]))
odd = dict(zip(odd[::2], odd[1::2]))
even.update(odd)
return even
any speed improvements can be made here?
Hey
Hey guys, I'm working on a web project based on python-django and trying to push it to heroku. but I get a rather strange error.
remote: -----> Building on the Heroku-20 stack
remote: ! No default language could be detected for this app.```
when forcibly putting ```heroku buildpacks:set heroku/python```
it returns ```
remote: -----> Building on the Heroku-20 stack
remote: -----> Using buildpack: heroku/python
remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
but since I'm making a site according to the guide, it looks rather strange.
code source: https://github.com/KoTeD0/learning-log
if someone can help me with push and build on heroku i'll be very helpful
omg... just fixed my problem. i just fucked-up with name requirements.txt it was ```requirments.txt
lol
so i have this html with some variables on it, can i get it using bs4? I replaced the variables with #
<div class="gameTimes">
<div class="localTimes">
<p>Local Reset Time: #</p>
<p>Time Until Reset: #</p>
</div>
<div class="serverTimes">
<p>Server Reset Time: #</p>
<p>Current Server Time: #</p>
</div>
</div>
hey guys, i am coding a small web server that can return different kickstart files according to the username passed. My current thing is, when i send something like http://ks.myserver.com/kickstart.ks?user=myname I get kickstart.ks?user=myname back as filename. which is not what i want. i just want a kickstart.ks file
i think this is called scrubbing?
i want to tell the client to save the file in the correct filename
or do something on the python server side to return the correct filename
Hi guys,
I have a flask app, so when I hit on routes which are not in the same file, it always throws 404 not found error:
Directory structure:
-> user
-> __init__.py
-> models.py
-> routes.py
-> app.py
app.py:
from flask import Flask
app = Flask(__name__)
from user import routes
@app.route('/') # THIS ROUTE WORKS
def index():
return '<h1>HOME</h1>'
if __name__ == '__main__':
app.run(debug = True)
routes.py:
from app import app
@app.route('/register', methods=['GET']) # THIS DOESN'T WORK - 404 NOT FOUND ERROR
def register_user():
return '<h1>Register a user!</h1>'
so i'm guessing you're running only app.py, and so routes.py is never run, and thus that route is never registered
you need some way to make sure that routes.py is run as well; one way would be something like
-> main.py
-> app.py
-> user
-> __init__.py
-> models.py
-> routes.py
```, and the `main.py` would be something like
```py
import user.routes # importing it runs the file and hence the routes there are registered
from app import app
app.run(debug=True)
``` and then run the main.py file instead
there are possibly other ways but i remember doing something like this once 😅
@high breach
yes?
oh i just answered your question, figured i'd ping in case you'd miss it
@gray lance ?
hm?
how do I remove the first div of the parent div with id='myTable11_wrapper'?
Sorry for the off-topic question, but perhaps someone knows. How can I deploy a FastAPI application on IPFS hosting like Pinata or other? Are there any instructions?
I need to process requests like this one : domain.eth/request
how can i use text-align: center; on <a> tag i've tried css display: inline-block; text-decoration: none; color: black; text-align: center;
change display to block
tnx
pls help
<script>
const parent = document.getElementById('myTable11_wrapper')
parent.children[0].remove()
</script>
i m using d3 svg map and i have 2 data, one for map, and another my custom data to plot the data points on the map
this is the map data const mapDataUrl = 'https://d3js.org/world-50m.v1.json'
i want to colour the country which has the data point in my custom data
this is the sample of my custom data to plot the data points, like here the country is US, so i want to fill some colour to US
pls help me do this
// load map data
d3.json(mapDataUrl, mapData => {
const countries = topojson.feature(mapData, mapData.objects.countries).features
g.selectAll('.country')
.data(countries)
.enter().append('path')
.attr('class', 'country')
.attr('d', path)
.on('mouseover', function (d) {
d3.select(this).classed('hovered', true)
})
.on('mouseout', function (d) {
d3.select(this).classed('hovered', false)
})
.on('click', clicked)
// load ip data
d3.json(dataUrl, data => {
const colorScale = d3.scaleOrdinal(d3.schemeBlues[2000]);
g.selectAll('.meteor')
.data(data.features)
.enter().append('circle')
.attr('class', 'meteor')
.attr('r', d => calcRad(20000))
.attr('fill', d => 'blue')
.attr('cx', d => projection([d.properties.loc.split(', ')[1], d.properties.loc.split(', ')[0]])[0])
.attr('cy', d => projection([d.properties.loc.split(', ')[1], d.properties.loc.split(', ')[0]])[1])
.on('mouseover', handleMouseOver)
.on('mouseout', handleMouseOut)
})
})
question on Flask \w Jinja templates, is it possible to pass a function to a view as a variable and reference that python function in an onclick property for some button in the view? looking for the best way to do this if possible
Are you hoping for the click to run this Python function? This is not going to work.
What were you hoping to do?
yes, and avoiding writing the pure JS version
The browser cannot run Python code directly. If the click handler needs to modify something on the client side, then you're going to have to write it in JS.
You can trigger a function to run in your Python backend if you set up a way to communicate between the client and server (e.g. an API)
yep, have an api
Then you need to write JS code that will make a request to your API
got you 😦
how can i make a dashbord for my discord bot
use a framework and interact with your bot through an API
What's the best way to return an image to the user from an external url such as ibb.co in a way such that it acts like it is a local image?
Im wanting to replace a send_from_directory return to get an external image and return it in the same way
flask btw
i figured out a work around, but this would be nice to know for future projects if anyone knows ^^
Hi
What framework(s)/setup/configuration do you recommend for a project that is asynchronously and constantly reading live data, processing it and then showing it in a website? At the moment, I'm using asyncio loop that runs forever that feeds an object and asyncronously detects changes in a "communication object" and send those changes through a websocket. But I feel it is very clunky, a lot of global variables, while True loops, etc
How would you "structure it"
Django Channels
Or FastAPI
Not sure which one of them
Choose only one of them
Dunno. Never worked with web sockets.
I only know that Django channels allows to work with web sockets and had as a example how to make a chat
Django is pretty structurized out of the box
If u look for some enforced structure
FastAPI as far as I know, best async framework
So could be nice choice too
I dealt only with django before though
thanks
pls help me with this..
hey i was Unable to set default value while using useState in react. I am working on a project where i give the input number in the input box and it returns the graph contains the same number of data samples for that i am using splice to list the desired number of samples from the data list. But when i give 5 i am getting 4 i dont the reason.
https://codesandbox.io/s/pensive-dust-g6ztxn please check the code sand box. It contains all my code
Probably not, you'll most likely want to know how to use JS frameworks such as React as a web developer
Technically u can, since python is backend language to make Rest APIs.
But know that knowing JS is still obligatory for any Dev in web development, if the person is beyond junior level
At least basics of it
Ideally yeah, js is used to make properly frontend in react/Vue.js
Then the person becomes backend person that can pretend to know some frontend
And yes, js is the main language of Frontend languages
There are no alternatives
Only things like typescript, which is just mypy'ed(static typed) extension of javascript
If u make some normal pages in python backend, u still need to use sometimes js as addition
But usage of vanilla js is a great perversion and ugliness
If u need js in python backend, better to make static linking to vue.js, to use it for much easier js syntax.
It is possible to use vue.js inside of any backend framework
Ideally frontend is made separately though
Because then person has full access to all things with js npm package manager
Guys I need urgent small project
For web development using css html bootstrap java script, and my sql
how to force a redraw of the browser content in brython (js)?
im gonna do it
Omg-
main.py isnt a taken domain
or like
{urname}.py
its paraguay managed domains tho so its cheap, but id guess their servers are asscheeks
Probably, but how chep? It's 170€ as I can see
Damn-
big yikes
Wrong site for me then xD
yeah right
probably the name tho
main is literally taken for everything but .store and .tech
i found this really old website from 1996 http://www.dolekemp96.org/main.htm
they forgot an l at the end of the link
but still it's nice
Hey everyone! I've got a help channel open but it was suggested I post here as well. I've got a pretty specific question I'm hoping for some guidance on.
I have a Flask application that uses HMAC headers for authorization. I have all the documentation for how to properly format your headers and I need to insert the info into an API page.
So I need to make a custom security scheme for my HMAC authorization. I am having trouble finding a good example to follow.
It appears Redocly doesn't support HMAC headers out of the box. Like it does for OAuth1.0 and others
I'm over in #help-chili if anyone has some assistance for me
i am having trouble with authentication
Anything?
never heard of that
looking to get signatures on django forms
In Django I have a form with a ModelChoiceField which queryset can have 1k+ entries. That would be pretty heavy performance side and I want to avoid the user to scroll a huge list. What are good alternatives?
Im setting up a tiny form but I cant get the "submitted" part to stay on the screen before it reloads
can I set up a timer?
or stop the page from reloading?
setTimeout?
ill try that
as it is advised to change the secret key in django settings.py
so while changing the security key, do I need to make some other changes also somewhere?
It's just a key that is used in the some of the security features that if a malicious person knew it, they could invalidate the built in CSRF protection and stuff like that
if you're talking about preparing a production server, there is a lot of things to go over to really be ready to do that.
i just generate one with import secrets;secrets.token_hex(32) and stick it in there.
can you please tell me those things?
like changing the key, debug=False, and..?
so i dont need to make other changes related to secret key after changing it?
well, they are a great deal of things that you really will have to read about extensively because those things you mentioned are just getting started.
as for the key, no. You just change it and it automatically does its job as long as no one knows what it is and its sufficiently unguessable.
If you're not pushing to production or anything dont worry too much yet but eventually digital ocean has good guides
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04
https://www.digitalocean.com/community/tutorials/how-to-harden-your-production-django-project
there's tons of them
Django is a powerful web framework that can help you get your Python application or website off the ground. Django includes a simplified development server …
i also made these changes
https://stackoverflow.com/questions/65172313/how-to-get-rid-of-django-security-vulnerabilities-warning-signs-in-terminal for security
I have a simple Django project with a PostgreSQL backend and I can't seem to get rid of the Django security vulnerabilities warning signs on my terminal.
Settings.py:
import os
...
ENVIRONMENT = os.
thanks for this
thee thing to remember is dont take production lightly. There isnt a checklist to be secure. You make mistakes and its not secure. so you have to know all the things that can happen and stay read up on all of it. As long as you knw that going in, and dont think it's magic and safe, you'll learn it as you go
got it, thank u
it helps imo when you start playing with having you own test production server to dabble a bit into penetrating testing on it. You dont have to go all in on the career of professional pen testing for clients. Just... try to break your own server.
and look up how to do it
common misconfigs etc
but run your test server pretending its a real production server and having it set up exactly like one.
okay, good idea
If an API uses cursors to paginate its results, how am I supposed to send concurrent requests to fetch multiple pages ? Because in cursors each page depends on the previous one
Hi everyone its my first time scripting a website and i need help
I run my code and it gives me a link to open it (im using flask)
but i keep on getting problem
Show us the output of your console
Also did you write any view ?
how would i go about determining if my sqlite database has been updated and send that to my websocket i have working now in django?
i've read some about redis, but im not sure as most things using websockets are just chat apps and im not sure of what is exactly what i am looking for
You can use django signals instead of subscribing to events from the database itself, that's easier but not sure if it's the best way to do thing.
from just skimming does this sound about right, when someone else submits something/updates something i attach a signal to that to tell the websocket to update?
Yeah exactly
I am sure there are ways to subscribe to events from the db itself but I don't know much about that, I think for what u need this should suffice
i could of swore i read something about subscribing to db events, but i dont see why signals wouldn't work in my case for the amount of users ill have
thanks!
hi
how can I add HTML and CSS and JavaScript into flask web?
I mean whole file of HTML
learn how to pass a jinja2 template to the view. Then in the template, you would load in the javascript somewhere.
and css
a template is just an html file with special syntax to conditionally load the html and other types of normally static content
hey guys
I am a beginner web dev
I am interested in learning more about web security and how to become the guy who protects websites from being hacked....
I have been browsing about it but can't find anything useful related to it
I want to know how to become one...
so, If anyone knows anything about this please share....
Things like networking, server hardening, are some important things I can think of to help you become of those people
Aside from the server side configuration, it might help to understand how web applications work, if you haven’t already. Then you can look into topics like CSRF, session management, file upload vulnerabilities, SQL injection, XSS. Also frameworks and libraries have their own vulnerabilities, which you can look into as they are generally specific to the versions.
There is obviously more, but the ones listed above as well as the comment above about server security should be enough for the basics.
Does anyone know if there's a decent way to use flask_login and firebase? I've found documentation from a couple of years ago but I think it's deprecated by now. There's not really anything else that's clear on using the two now.
im getting a error while submitting the form
Direct assignment to the forward side of a many-to-many set is prohibited```
but working fine via admin panel
class Product(models.Model):
title=models.CharField(max_length=50)
price=models.IntegerField(default=0)
pic=models.ImageField(default='default.jpg',upload_to='images')
published_by=models.ManyToManyField(User)
desc=models.TextField()
published_date=models.DateTimeField(auto_now_add=True)
slug=models.SlugField(max_length=35)
def __str__(self):
return self.title```
@login_required
def seller(request):
if request.method=='POST':
title=request.POST.get('title')
price=request.POST.get('price')
pic=request.POST.get('pic')
published_by=request.user
desc=request.POST.get('desc')
slug=request.POST.get('slug')
if Product.objects.filter(title=title).exists():
return messages.warning(request,'TITLE ALREADY EXISTS')
if Product.objects.filter(slug=slug).exists():
return messages.warning(request,'ENDPOINT ALREADY TAKEN')
added=Product(title=title,price=price,pic=pic,published_by=published_by,desc=desc,slug=slug)
added.save()
messages.success(request,'Product added')
return HttpResponseRedirect(reverse('index:home'))
return render(request,'index/sell_product.html')```
I want to make library management system with crud operation in django ? Please can tell how to do that?
simple
first make models
for that imagine all the functionality of the web-app u're gonna make
I want it create
Add a book
Update entry book
Delete a book
Get all books
So I have to create only one class
yeah!
class Books()
#fields here u want
n if want any class to be on child/connected/linked
use can create below n use rdbsm
What is the easiest way of making async calls in django
With ajax or there is a native way in django
I have to make loading screen
#cybersecurity could help you with that, last time i was in there it was about php password sign-in security and how to prevent it
Django has nothing for frontend except Jinja templating language
If u wish more Frontend, use frontend Frameworks.
Or at least make static linking of frontend Frameworks like vue.js into Django to enable it from inside
Anyway inside Django templates u can have only frontend that u can statically link.
I think jQuery can be enabled too
Yes I have done it in react but not in any django only site
Thanks for the help 👍👍
If u use react then...
Continue using react. Use Django as rest API to react ;)
Django, API, REST, Home
counter {
transition: --num 1s;
counter-reset: num var(--num);
}
counter:hover {
--num: 31;
}
counter::after {
content: counter(num);
}
how can i make this count up without needing to hover over top of it? Like can i edit this with js? without needing the hover?
When do u wish to trigger
On page load?
well i have a splash screen that lasts 2 seconds. 3 seconds tops because its element gets removed
i tried using settimeout and making the hover a counter.animation {}
but it didnt seem to work and my js is lacking
U can trigger transition by adding class with js
Turn hover into class
And add it when to start
i did that using ```js
setTimeout(() => {
document.getElementById('counter').classList.toggle('anim'); }, 2000);
it didnt seem to work
my js is bad dont bully me
It's set interval btw
Vanilla js... It is awful to use in general ;)
oh.
Frontend frameworks for the win
well i started using a different script
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 7555,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
css:
.counter {
display: table-cell;
margin:1.5%;
font-size:50px;
background-color: #0077B6;
width:200px;
border-radius: 50%;
height:200px;
vertical-align: middle;
}
html
<div class="counter" data-count="31">0</div>
output:
Check svelte out of curiosity.
Although I would usually recommend only react or Vue. Js
That is jQuery, i think
might get rid of the text
yeah i do ALOT more work with jquery
it just feels better personally
jQuery is just vanilla js on steroids
thats why
Frontend frameworks much better
omg im so dumb
if this works
im sorry
but like
nvm
didnt work
anyways
<h3>Now in <div class="counter" data-count="31">0</div> servers!</h3>
<script>
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 7555,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
</script>
didnt seem to work
i did alot more than i needed
const box = document.getElementById('count-up')
let count = 0
const countUp = setInterval(() => {
let boxCount = box.dataset.count
if(count == boxCount) clearInterval(countUp)
box.innerHTML = count + box.dataset.unit
count = count + Math.floor((boxCount/31))
if(count > boxCount) count = boxCount
}, 20)
css:
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
background-color: #1E1F26;
}
#count-up {
font-size: 2em;
color: lightblue;
font-family: Verdana;
font-weight: bold;
letter-spacing: 4px;
}
html:
<div id="count-up" data-count="31" data-unit=" servers"></div>
i hate my life
ended up creating a settimeout so i could activate it after the splash is finished
Hey folks
What approach do you use to integrate react and Django together?
- Build a standalone react app and host it separately
- Serve react app from Django.
Please share your insights and why do you prefer your approach.
Building standalone react app, because it is the way to microservices architecture
Better scalability with code growth
Using methods less than that makes sense only in some pervert situations with really silly restrictions
Thanks for sharing your feedback😊
U a welcome. Also as a point...
People use less than that because they don't know Infrastructure instruments
Already with docker compose it should not be an issue
@inland oak And what mechanism do you use to build real time apps with django? Channels or some third party services like Pusher
And because people don't know Auth methods
Not developed stuff like that yet, but I am eyeing my choice between Django channels and FastAPI as first candidates
You mean people serve react with Django?
How is this related to authentication? Can you please explain this to me
I serve vue with nginx
That's what I like to do. Serve standalone with Apache or nginx
I specifically use nginx-unit because it can run my asgi app too
That's pretty awesome. I too use nginx to serve react app.
For backend- Django I deploy it with containers on Google Cloud. I also use app engine
i have some questions about this:
should i have the text inside?
should i use just the number itself?
if i do; would people notice its the amount of servers and users with the icons i have in place?
should i use a gradient? or have a still color?
should i use animations on them? or just the static images itself?
i get alot of hate because of how this looks and im now finally going to change it. i dont want it to look like complete shit
Not familiar enough with React, but people differently can serve Vue.js with django
There are different ways to Auth users in order to keep them authed. In built Django methods for frontend Frameworks we can probably find in DRF.
The point is... With microservices architecture, we have multiple backends, and we Auth only in one from frontend, and to be not validating in one database?. How do we achieve it? How to create tokens for temporal URLs of email verifications and password resets, which we could create in backend, and accept in frontend?
The answer to everything is JWT.
Which is the way to keep a dictionary of key values with user info and rights, validated by your secret key.
People at the beginning not really familiar with Auth stuff to use microservices freely
With one just Django they could use inbuilt methods with minimal understanding how it works 
is there anyone to help me
A guide for how to ask good questions in our community.
whats the different between css and scss
scss is css with sass
scss supports pre processors and nested rules
You can also get variables via ```scss
$red: #FF0000;
body {
color: $red;
}
Do I have to manually set a httponly cookie? I'm getting it in the login POST response, but then when my flask backend tries to access it on another request, I get no access_token cookie response message
ping me if you know, but whats the advantage of using python over html for web dev?
Django-rest-framework: If I put the token authentication class in the class list settings in config, Token Authentication does not work. It only works if I put the class in the view class variable
# does not work
# myproject.config.settings.base
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
# works
# myproject.views
class MyListApiView(generics.ListAPIView):
authentication_classes = [authentication.TokenAuthentication]
serializer_class = serializers.MySerializer
I really don't understand why TokenAuthentication class specified in the settings won't work, but if provided in my view it will. SessionAuthentication works fine and it's specified in settings....
can i get help with hugo here?
i might be mistaken but isn't hugo writen in go?
the pages are written in .md
thats just markdown its a fancy text file
anyone that can help me with js?
ask away
im tryna make a small zombie game where some zombies chase after 2 players, but i can only get it to only go after one or have it so that one of the players control X axel and the other one Y
if (zombie.x < player1X) {
zombie.x += zombie.speed;
}
else { zombie.x -= zombie.speed;}
if (zombie.y < player1Y)
zombie.y += zombie.speed;
else { zombie.y -= zombie.speed;}
```
this what i use, you know how to fix it?
tested adding the same script twice but change the variables for the other but it wouldn't work
uh oh, logic errors
you know how to fix it?
nope.
ok, thx anyway
fair
that's also my typical debugging strategy
hello if anyone knows selenium and they are free can you dm me plz
A guide for how to ask good questions in our community.
Has anyone integrated django channels and react together?
Can anyone share link to such projects?
i did not, but tutorials in django channels look pretty sick https://channels.readthedocs.io/en/stable/tutorial/part_1.html#creating-a-project
it looks like not a hard problem to rewrite from vanilla js to react
Sure thing. I would look into the documentation.
Thanks ..
I am formatting a book in a HTML file and I only want it to be in a single HTML file. I was wondering how I could make the table of contents clickable so that I can click a part and it will scroll to that part
i think hyperlink tags might help.
https://www.w3docs.com/snippets/html/how-to-create-an-anchor-link-to-jump-to-a-specific-part-of-a-page.html
Thank you so much! It worked as I wanted it too
Is there a way I can make it so the text isn't blue though?
I found out how
How do you send a post request after a button click or after any other action except sending input to a form?
With php?
&_POST
using django/flask/python/javascript/html/css as this is a python server
Or something
Ah
Html
<a href
Or javascript on click
Html for ur example is easier
but what about if you want to click a button to search a database and then outputs a result?
Php
Thats the only thing i know
Idk about flask but for that i use php
Common use for that
Just search on google lmfao
Check out events and how to add event listeners. If you're in a form, you can catch the submit event. If it's a button, you can catch the click.
Here's some docs for the click event:
https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event
Check out Fetch API for sending requests and handling the response
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Hopefully with these two resources you can string them together to do most of what you're asking about..
thanks! is it also possible for a button to make a form with no inputs and just a submit button, and send a post request in that way?
yup
If you're using Django, you can use the forloop.counter or equivalent builtin for their templating
https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#for
Please Where to put that for loop in above code?
Inside the cell where you want the current index, the No. column
Thank you buddy
It's working 🎉
https://www.synopsys.com/glossary/what-is-owasp-top-10.html start from OWASP 10 and go further
The worst security paranoia is intended for any web sites that deal with user payments
and even 10 times worse security paranoia for web sites which KEEP user data for payments
and even Worse than that, if the web site have a really big amount of transactions
In order to pass those security measures, the person is required to go through PCI DSS complaince https://stripe.com/guides/pci-compliance here you can find documents regarding that
As far as I remember electronic commerce web sites which do not store user data, need to pass only lightweight 80 pages PCI compaince version
And those who keep user payment data, there should be document for 300-600 or more pages
The OWASP Top 10 is an awareness document for Web application security. The list represents a consensus among leading security experts regarding the greatest software risks for Web applications. Find out at Synopsys.com.
Found
Lightweight PCI DSS compaince is SAQ A-EP category
A-EP
E-commerce merchants who outsource all payment processing to PCI DSS validated third parties, and who have a website(s) that doesn’t directly receive cardholder data but that can impact the security of the payment transaction. No electronic storage, processing, or transmission of cardholder data on merchant’s systems or premises.
Applicable only to e-commerce channels.
Here is the lightweight, 55 pages security check for the situation A-EP above
Security is a thing going all over the architecture of the web sites, in frontend, backend, infrastructure. PCI DSS Compaince summarized all the weak spots the organization should check and security measures to implement for any type of product
Security can be in your code, to fix all the default settings
Security can be different ways you implement encryption / storage of user data at server and client side
Security can be using Vault secret storages
Security can be in setting up permission managing system for your system admins
Security can be tools that make automatic checks for the password leaks to to git or docker images
Multiple was, PCI DSS complaince tells you that
Lets say, there is a reason why big corps have Security departments and even DevSecOps profession was born 😉
Yes. compiling to PCI DSS compaince is part of Stripe 😉 They help to guide to to make the ride as smooth as it is possible
I discovered about PCI DSS complaince because I tried to add Stripe in the past
https://www.pcisecuritystandards.org/documents/PCI-DSS-v3_2_1-SAQ-A_EP.pdf?agreement=true&time=1648025173211
Try to make sense of A-EP self assessment for attestation of compaince
it should be the easiest possible way to get Stripe and being security complaint, just 55 pages
as long as u make sure
A-EP
E-commerce merchants who outsource all payment processing to PCI DSS validated third parties, and who have a website(s) that doesn’t directly receive cardholder data but that can impact the security of the payment transaction. No electronic storage, processing, or transmission of cardholder data on merchant’s systems or premises.Applicable only to e-commerce channels.
help mee plz the content comes up i import the navbar by include django
Hi, I needed some help with datetimefield serializer
This is what I'm facing
help please https://stackoverflow.com/questions/71585508/navbar-dosenot-come-up-and-it-under-the-content
using selenium webdriver, how do i tab between buttons? not the tabs, but the tab button
because if you press tab, you cycle through pressable UI stuff, even on discord
i want to do that in selenium, but to any (clickable) element i want
this means no pyautogui or keyboard simulating
ping me pls
Anyone got an example of a django login/sign up split page ?
Guys, I have a question. If user request page that consists only from empty form that I think can be done on front. Should I send any data with DRF views or process GET request? Thank you in advance
oi is any1 here free to hold my hand a bit? i got thrown into a html class and im kinda lost
Discord has recaptcha on login, selenium gets detected
There is a little I’m not a robot thing, just letting you know before your hopes get high, also I believe that there is suck a way to simulate key presses, look in documentation, I used it once
Such*
bro
i told you i want to "tab" with selenium
like select what (clickable) element i want
Did you want to select an element or press tab
select an element
which is basically what tab does when you press it
but when you press tab it won't select whatever element you want
and how do i select it
focus or click probably
You should really read the documentation
Documentation explains how to select stuff, Reading it for selenium is especially important because it’s designed for this stuff and tells you about it
show me where it says how to select stuff
and again, how do i do it for that
Google selenium select elements
bro
that's basically "do it urself"
which is bs
because that is why i am seeking help
to get help not be told "do it yourself"
if you have an open page of the docs, then give me that page
also i found nothing
doesn't say how to focus
im following tech with tims tutorial on flask and im getting this error
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Note.notes - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
the line of code it says is wrong is the following
new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256'))
if you need the full script i can send it to you
can I see the class of User
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(150), unique=True)
password = db.Column(db.String(150))
first_name = db.Column(db.String(150)) ```
in models.py
sure
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.String(10000))
date = db.Column(db.DateTime(timezone=True), default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
notes = db.relationship('Note')
move the notes in the Note model to the User model
the notes variable to the user or the entire thing?
Like this
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(150), unique=True)
password = db.Column(db.String(150))
first_name = db.Column(db.String(150))
notes = db.relationship('Note')
class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.String(10000))
date = db.Column(db.DateTime(timezone=True), default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
works?
im not getting the error anymore but im running into a different problem
whats that
so i get a POST request in my terminal when i submit the sign up but it isnt redirecting to the home page like i want it to. else: new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256')) db.session.add(new_user) db.session.commit() flash("account created!", category="Success") return redirect(url_for('views.home'))
but when i click it twice to see if that works it sends me this error. sqlalchemy.exc.IntegrityError
Send the whole error message
[SQL: INSERT INTO user (email, password, first_name) VALUES (?, ?, ?)]
[parameters: ('jim@tim.net', 'sha256$P71mjW74TbTnzQXT$bb2c0dc2a7b50933f7a1ab3a6450e85e7863a4c4c261be536d1fc68a68b2d7f0', 'jack')]
(Background on this error at: https://sqlalche.me/e/14/gkpj)
I try to migrate this but i get one error,even after deleting the whole salary field i get the same error
Its should show an error on the website
If u have debug on
that is the error on the website
can you send the more of this block?
def sign_up():
if request.method == 'POST':
email = request.form.get('email')
first_name = request.form.get('firstName')
password1 = request.form.get('password1')
password2 = request.form.get('password2')
if len(email) < 4:
flash('Email must be greater than 3 characters!', category='error')
elif len(first_name) < 2:
flash('First name must be greater than 2 characters!', category='error')
elif password1 != password2:
flash("passwords dont match", category='error')
elif len(password1) < 7:
flash('password must be at least 7 characters', category='error')
else:
new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256'))
db.session.add(new_user)
db.session.commit()
flash("account created!", category="Success")
return redirect(url_for('views.home'))
return render_template("sign_up.html", user="current_user")
can you send a screenshot on what is says in the website
wait its working now
so i guess since im using repl.it, if you try it in the preview window it doesnt work. But if you open your website in a new tab it does work
thank you so much for your help
np
python communities are so much nicer than javascript communities
can someone help me with this
javascript community:
is trusted maintainer of widely used library
Uses it as a protest platform
I'm looking for a hobby project to work on. If you are working on something and you need help please let me know and I'll be happy to help you if it interests me.
r u running makemigrations command?
please suggest me some of the django projects videos/tuts for practice ..
There are a lot of videos on youtube . Check out the channel freeCodeCamp
yo guys, whats good to start with for learning web dev, js or html and css?
yes
i think u may to delete the whole data now to resolve it maybe
how do i add a loading animation with flask ?
can anyone help me with a question i have on hugo the website builder
I’m new to flask and have been looking into creating my first login page. Most of the documentation that I have read uses a database to pull username and password then verifies it. I was wanting my program to login by confirming the username and password with an external API, so when the login form is submitted, an API get request is made on an external server, if you get status 200 then login if 401 then credentials failed. Is this something that’s possible?
!pypi authlib this is also an option. it supports many backends
In Django, is it possible to update a relationship "backwards"? For example, model.objects.update(x=[1, 2, 3]) where x is the related_name of a foreign on some other model.
I know it is possible with .set(), .add(), or .remove() if I have a specific instance of the model. But I want to do it in bulk like shown above.
By the way I tried it with that exact syntax and I get the cryptic AttributeError: 'ManyToOneRel' object has no attribute 'get_db_prep_save' which comes from some Django internal stuff but ultimately originates from that update() call.
I'm working on a rather large scale project using Python and some JS, FastAPI, disnake among others. I'd be happy to share more about it.
perhaps some simple example of your issue would help but I think the answer is no, you should update it from the other side
but I think it's still possible to do in bulk
I thought I already gave an example but I can elaborate. I have two tables, A and B. Table A has a FK to B, and its related_name="x". Thus, B.x exists.
Let's say I have a three rows in A with IDs 1, 2, and 3, respectively. I want to make all three rows relate to the same B. I want to be able to do something like B.objects.filter(pk=1).update(x=[1, 2, 3])
yes sorry, it just still wasn't clear to me.
So instead you should get the queryset for the A model and I think you can update the foreignkey in bulk
A.objects.filter(id__in=[1, 2, 3]).update(b=B.objects.get(pk=1))
Thanks. For some reason I was imagining it to be more complicated to do in the other direction but that's not bad at all.
np
A.objects.filter(id__in=[1, 2, 3]).update(b=1)
I think it's valid to just give the pk of the foreign key
I'm trying to execute a .py I created inside a django app, but it keeps giving me this error everytime I try to import a model from models.py:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I wanted to dump some scrape into the database, and the scrape.py (file I'm trying to execute) works completely fine until I import the BlogPost model, which comes from model.py
The app is already added to the "INSTALLED_APPS" area, that's why I'm not understanding why it's saying it's not configured. I did run migrations already.
some set up happens when you start up a server or get into the django shell that doesn't happen if you just try to run a script directly that tries to utilize django's models
you'll want to run that script inside of the django shell or maybe it's possible to do what they're saying and run settings.configure() at the beginning of your script after importing from django.conf import settings
your options are
- create a management command https://docs.djangoproject.com/en/4.0/howto/custom-management-commands/
- do the settings.configure() thing
- run your script inside of the django shell
python manage.py shell < myscript.py
if it's just a one time thing, I'd just do the 3rd option
if you'll use this over and over again, I think making a management command is good
Then you can call it easily like python manage.py mycommand
@untold scroll
thanks a lot @indigo kettle I'll try it now
here's this as well https://stackoverflow.com/questions/16853649/how-to-execute-a-python-script-from-the-django-shell
django-extensions is a popular add on for django and they have a nice runscript command as well
https://django-extensions.readthedocs.io/en/latest/runscript.html
I'm trying to apply this constraint in Django, which is supposed to disallow a null sensor_id if the type is NOT "man"
models.CheckConstraint(
name="auto_sensor_not_null",
check=~models.Q(type="man") & models.Q(sensor_id__isnull=False),
),
However, the migration fails with an error stating that some row violates this constraint.
When I print the rows of the table, there is only one row that has a null sensor_id, but that is the one case where it acceptable since the row has "man" as the type.
1 param1 None man
2 param2 0 auto
3 param3 1 semi
What am I missing? Did I write the condition incorrectly?
Ah yeah I forgot something. It's failing because the type is manual. I need an | models.Q(type="man") to allow it
But then it just simplifies to models.Q(type="man") | models.Q(sensor_id__isnull=False)
So yeah, problem solved.
Hey guys, this is probably a more opinion-based question rather than one with a definite answer, which is why I'm posting here. I currently have a Django app set up so that it auto-generates a secret key, and writes it into its settings directory when it doesn't detect a key file. Are there any major security implications I should be worried about, or is this approach solid?
I don't see anything wrong with that. As long as it's generating strong keys.
This approach is silly
You need to keep the same secret key
In order to have users auths kept valid
Depending on where is it used, their passwords hashes can depend on it
And additional sillinies that u keep persistent data from Django
It is not great. Better to keep it as stateless as possible
While moving all persistent data to dbs
It is more... Cool for future infrastructure development
More room for flexibility with it
Like deploying in AWS your app as container application directly
Secret keys should be injected as env variables
Well he said it only occurs when it doesn't detect a key file. So it's just a one time thing. It would be the same as going into your python REPL, generating the key, and pasting it into your .env file once.
So it should be fine if that's what he meant.
if you deploy an app with this strategy I assume the key will get overwritten on deploy because the secret key shouldn't be stored in the repo. I supposed it could be, assuming that the repo is private but then why would you generate a key at all, just hardcode it
I don't like the writing to file step. It assumes the application willl be having persistent attached volumes. Unless there is a critical emergency for that. Django container should not have it
plus defaults should be treated carefully. And in my opinion, secret key is the thing you don't want to fall back to random default, better to get an error if the env is not provided
Yeah, absolutely that's all true. Wasn't thinking about that since all he asked about was security implications.
That's true. Thanks for the feedback.
what's a good way of versioning?
Django, API, REST, Versioning
I want to do url path versioning
isn't making another app better then just point the url to that?
django btw
does anyone know how to get the image metadata uploaded UploadFile method of fastapi? as per docs, it only declared filename and filetype, but i need specific metadata like image dimension and dpi
Okay .. thankx
Hello i getting error in template of html
NoReverseMatch at /
Reverse for 'edit-book' with arguments '(1,)' not found. 1 pattern(s) tried: ['edit/\Z']
Hello everyone.
I want to make a website where I can write code and execute or run the same code and it gives the output. Basically the problem is that I want an online code editor or compiler which supports multiple languages, how can I do this?
so.. replit? or heroku? or w3schools?
heroku is a deployment server
right
what I have to do?
i have no idea
you probably need to setup like
virtual envs
and storage, vcpus, vram, etc
ok thanks
I mean if the content isn’t found, can’t be retrieved, can’t be parsed there would be an error
Replit
U gotta do replit
i mean for example, the user and group doesnt exist
replit is bad
I 100% reccomend replit
what is replit
It’s easy to install stuff, run discord bots, websites, tkinkinter etc
doe it's superseeded by pycharm, better than vsc(web version)
Don’t use it. Check out VSCode
If you want free and online I recommend
yes I want free
VSCode
The ide got a theme update which I hate but hey it’s great for free
it supports all langguaes?
VSCode supports almost all languages
It supports a ton considering it’s free
just get visual studio code, or PyCharm Community (for more... difficult projects)
He wants online
ah
GitHub workspaces allows you to use a VSCode like editor in the browser
Just get VSCode app
also its ran by vsc
Should I clear my complete project details to you all so that you can suggest me which is goo
But you can deploy a flask server hella damm fast on replit
good?
why do online code editor tho
I know a guy who runs s api and discord bot on it
Please don’t use replit…
And I’m setting up a bandwidth miner on it
I work on flask
Ye I recommend
Don’t ever publish anything unless you are fine with people stealing code
i use it for web dev but i also put its cname through cloudflare so it isnt 100% ass
It’s free u gotta love it
also can i use the exact same paramaters for text-shadow as i can for box-shadow
I am creating a website for my college for coding contests. In which questions will be there and when a student click on a question a new page loads having that online code editor(or compiler) and run the code on same time
I can do front-end, backend, database
are you gonna try and get them to get a specific output
Only problem I am getting is how to add that editor
yes
flask, underdeveloped websites, mostly for people who gonna make lightweight/low knowledge stuff
They have editor embed
except for a few who goes all the way with it, api's can be done efficiently (using multiple libraries)
the answer(or output) of that question only
literally thi
Experience everything then choose
https://codebattle.hexlet.io/ or this
any language
same output
is this for code editor?
for what your literally trying to do
it already exists
where?
How I can use and apply it to my website
i frame
I want exactly same page like this which has question(task) and editor
use codepen
or somethign
you can make the problem
share it to them
give them the task
means?
if they get it
theres people in the smae room
you arent on like
a meeting
call
Instead of replit, try a beginner friendly IDE like Mu or Thonny
online for my site
im still bummed over how webhook exception handling is done, if i get error in code do i just... leave it
you don’t need an online IDE to make a website
then?
i got a Of course git forgot to commit the fileno module named project.chat.models error when attempting to do import .models from project/chat/consumers.py to the directory project/chat/models.py. Settings file is located at settings/base.py, and project, chat and settings folder all contains __init__.py. Additionally, chat is added to the INSTALLED_APPS variable, and contain the correct apps.py format to be detected.
Hello everyone 🖐️😃
I'm new to python web development (extreme beginner), can someone help me from where should I start the basics to web dev using python like some tutorials or some advice will be helpful.
Thanks in advance innocent
first learn the basics of python (variables, lists, data types, functions, classes ect..)
if you already know that then choose a framework to work on such as flask, django or fastapi
and learn to work on that framework read a doc or go through a tutorial
Anyone have experience with azure hosting?
I've learnt basic python. I'm beginner in web dev field so which one will be most beginner friendly framework ?
flask is a pretty good place to start
yea I think flask would be good
dm me
I am creating a website for my college for coding contests. In which questions will be there and when a student click on a question a new page loads having that online code editor(or compiler) and run the code on same time
I can do front-end, backend, database
Only problem I am getting is how to add that editor
look into "ace editor", there's a few prebuilt js code editors but you'll have to handle compiling/testing the code yourself
Is this the right channel to ask for elasticsearch help?
anyone?
that wasn't soled
#help-potato i'm using flask, need help
flask beginner project ideas?
Just saw your message in the channel. I think you might need to provide an absolute path to the tokens.json file. I don't think your app is able to find that file, hence that TypeError's message
Can you share the complete exception? Hopefully it'll show specifically where it's erroring out
are you already past register and login Saki?
other wise a login, and register system are always a good start
@stable bear
yes
i would like something involving login and register as i know how to implement those
just make a simple system for it and load a page
so not logged in go to x page other wise go to y page
done that
alrighty next thing is then have you done much with databases yet?
with sql alchemy?
I'd suggest focusing on a blog site with articles, or if that is to much a permission system with users
where different users can access different pages that others can't
that should help you getting used to the relational database system
Hi, I seem to be having some issues with aligning these three images side by sidehtml <a href="https://github.com/anuraghazra/github-readme-stats"> <img align="left" src="https://github-readme-stats.vercel.app/api?username=SnowyJaguar1034&count_private=true&include_all_commits=true&show_icons=true&theme=nightowl" /> <img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=SnowyJaguar1034&repo=Zupie&show_icons=true&theme=nightowl&show_owner=true"/> </a> <a href="https://github.com/anuraghazra/convoychat"> <img align="right" src="https://github-readme-stats.vercel.app/api/top-langs/?username=SnowyJaguar1034&theme=nightowl" /> </a>
You should probably aim doing that with CSS or Bootstrap instead of inline HTML. It's much easier and makes the html less messy. There are a few articles that should be able to help you with that, I think this is a good place to start:
https://www.w3schools.com/howto/howto_css_images_side_by_side.asp
I'm trying to do this inside of a .MD file so the questionable choices continue. Is CSS supported in MD files?
Oh ok. Inline CSS is supported
but if it's for github I'm afraid they don't support it. It kind of goes against the purpose of .md files anyway to make things simpler.
Yeah it's for GitHub. It's annoying that CSS isn't supported but I kind of expected that
Hello everyone ! is anybody here familiar with CGI scripts ?
Hello ! I kinda wanted to learn web development using flask, but i found myself stuck.
Basically; i can't manage to call any "extern" css file, it just won't load, and i don't really know why since there is no output in the console.
( The screen at the bottom show how the folders inside my project are sorted )
main.py file :
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/home')
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
base.html
<html>
<head>
<title>Shrek Mania - {% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" herf="{{ url_for("static", filename="styles/style.css") }}">
</head>
<body>
{% block body %}
{% endblock %}
</body>
style.css
body {
background-color: black;
}
Hello I want to run a pick a number game that is made all out of python on a website how could I do this with minimal code needed
Not sure if you spotted, but you are spelling "herf" instead of "href". Also, remember to use single apostophe inside a string that was already opened with double apostophe
I’m building a Django web application. I need to build a user authentication system where a user can play the game three times, then after that get prompted to sign up or login. High level, don’t need the code, what would I need to do this?
I’ve already built the signup and login but how do I do the other part with letting the user access some features then making them sign up?
hey everyone..
can anybody help me understand this.. below code is a django CBV inherited from
class ProductSearchView(FacetMixin, HaystackViewSet)
this have a method called get_queryset... but i don't understand how this filtering going on..
queryset = super(ProductSearchView, self).get_queryset()
q = self.request.GET.get('q')
queryset = queryset.filter(owner_id=self.request.user.id)
if q:
update_stats.delay(self.request.user.id, q)
return queryset.filter(SQ(title=AutoQuery(q)) | SQ(sku=AutoQuery(q)) | SQ(text=AutoQuery(q))).highlight()
return queryset```
can someone help me with? i tried google as well. But i cant understand whats wrong
idk if its it but maybe its the space at the {% else % }
maybe you could also try an elif not recipe.cover?
dm me
U can do it easily with Flask
I have no experience with flask how you recommend I do it? I can provide code in a few days if that can help
dm me brother.
I will try to help you
Ok
can someone help me
with what
in new password and confirm new password, I m using regex pattern, bcoz of this the focus attribute is not working correctly as u can see
how do I make them work like the old password field?
<div class="user-box">
<input type = "password" name="oldPsw" id="passwordOld" required>
<i class="bi bi-eye-slash" id="togglePasswordOld"></i>
<label>Old Password</label>
</div>
<div class="user-box">
<input type = "password" name="newPsw" id="password"
required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$" title="Minimum of 8 characters. Should have at least one special character and one number and one UpperCase Letter.">
<i class="bi bi-eye-slash" id="togglePassword"></i>
<label>New Password</label>
</div>
pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$" is causing the problem
im adopting
Hi.
How do I add a variable for userId in this scenario:
On the underlined from the picture,
I tried to do the
f'{userId}'
and the triple quote method and the .format(userId)
It didn't work..
If my only option of retrieving something in javascript is calling this.a.b.c.target, whats the proper way to make sure a, b, and c are not undefined?
Also, does this situation have a name? Where you're calling the child of a child several layers deep?
Thanks
@royal river can u be more clear and please mind sending the code?
I'm fairly new to web development and want to make a web application that I can use to communicate between 2 separate applications. My only concern for now is, how do I make some sort of event in python? An event that is triggered when someone requests the web server?
no no, so what framework are you using
flask or django orrr
yeah so flask only does something if you send a request to it
if you send a request to a flask server its going to trigger a response naturally
doesnt django also do that..?
yeah django does that as well
since im new, i will explain what im trying to make
all backend frameworks work off requests
yeah ive made some practice websites with both django and flask
but for now thats really the only thing i understand
what i want to know is how i can communicate between this web server and another separate application
for example
how can i trigger an event in a discord bot if a request is sent to the web server
something like that
thats where im stuck
and its frustrating
i'm a bit confused what the file structure is supposed to look like in a standard django application
im trying to render a html
using django.shortcuts.render
but when i pass the html path its just saying it doesnt exist
i printed os.listdir() and it showed its in the root
but i tried every path and its just not workin
@ivory kiln I'm working on a Django project now (first) so I'll see if I can help. I assume you made the basic html template and stored it in the app_dir>template>app_name>html_file? From there you should have referenced it in app_dir>urls.py as a path on the urlpatterns? You also need to make sure to include the app_dir.urls in the urls.py under the project directory.
thanks, i fixed that issue
i have a question
cool stuff
im doing ```py
def index(request: wsgi.WSGIRequest) -> HttpResponse:
response = Response(request)
html = response.to_html()
return HttpResponse(html)
I'm trying to get view to only display when logged in. i got the logic done, but I kind of wanted to have a base.html that will be the same throughout, and then only show other elements when logged in. is the use for {% extends %}?
boom. love it!
@manic frost Hi again, is it fine if I ask for some guide on this insertion of variable from a string parameter.
How do I add a code in this chat with properly quoted one btw.
When I enter something in the input, and submit it, it won't show up. Can anyone help me figure out why?
templates/editor.html
<form method="post">
{% if results %}
{{ results }}
{% else %}
{{ editor.console() }}
{{ editor.run() }}
{% endif %}
</form>
main.py
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import validators, SubmitField, TextAreaField
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('key_thing')
class EditorForm(FlaskForm):
console = TextAreaField("Let's make some W# Code!", [validators.optional()])
run = SubmitField("RUN")
@app.route('/', methods=['GET', 'POST'])
def index():
results = None
editor = EditorForm()
if editor.validate_on_submit():
results = editor.console.data
editor.console.data = ''
return render_template('editor.html', results=results, editor=editor)
if __name__ == '__main__':
app.run('0.0.0.0')
FlaskForm has CSRF enabled by default and you need to include that hidden input. Here's an example: https://flask-wtf.readthedocs.io/en/1.0.x/csrf/#html-forms
For future reference, the underlying Forms object has an errors attribute that will show you any validation errors (after calling validate or in this case validate_on_submit).
How can I run a Python script in PHP with arguments? Do I just have to insert arguments after path like escapeshellcmd('path', args)?
Can someone explain how this function is working how is the result argument getting the "done !"String
after 1000ms, it calls resolve("done!"), which is a callback set to alert
it can be rewritten as this. ```js
(async () => {
try {
const result = await promise;
alert(result);
} catch (e) {
alert(e);
}
})();
hi, I need help, I am making a hover animation for my navbar, but I only want the text to have the hover animation and not the main logo, anything I can do, essentially I want to remove the hover animation for specifically the main logo (btw I am currently hovered over the logo to demonstrate
I’m wanting to write a web application that takes user form input, adds that to a queue, then once the user specifies they are done, it will run a python script for each set of variables (each form) that the user inputs. Is this something that’s doable in Flask? Should I look into other options? If so, could I get pointed to some documentation?
Forever thanking my bootcamp teacher for discovering Streamlit
Now that it's in version 1.x it's so useful
If I have a flask web app, how is it possible to trigger some sort of event in a separate python application once a request is sent to the web app?
the simplest way would be to start your other application as a subprocess
how would that work?
for example if you had a program helloworld.py you wanted to call when a flask endpoint was hit you would use the subprocess library to open a new process for "python helloworld.py" in the route code
alright, ill see how it works, thanks
i have just realized, what if the other python application is already running and i want to trigger some sort of event in it when a request is sent to the flask application
in that case you need some sort of shared state, your flask application will need to write to a file/pipe/database that your other program is monitoring
so there isnt some way to trigger an event in a separate application..
alright, how do you just make an event in python
just in general
a general event my code can wait for
I think you may want to do some reading on how interprocess communication works, the methods I mentioned are how you handle any sort of communication between seperate applications. "Event" queue's for instance are generally implemented using pipes.
alright ill research on that, thanks for the help
Have any of yall used the mediapipe hands library for any web development?
Or even for experimenting purposes?
I am new in web development can you suggest me to how to start it
@obtuse mantle Do you know how to code?
What I did a while back to learn how to code and create a website is create a web calendar. Kinda like google calendar. I made a small database to save all the dates and made a nice user log in interface that would also be stored in a database. And there are plenty or resources to use to learn how to make all the components of that.
So how create a database
You can use videos like this as refrence. https://www.youtube.com/watch?v=o1yMqPyYeAo But the more you do yourself the more you will learn
UPDATE: Unfortunately there is a glitch in the tutorial, the statement "monthDays.innerHTML = days;" should be placed outside of the for loop!!!
In this tutorial, we will build a Calendar with HTML, CSS, and JavaScript
SOURCE FILES: https://github.com/lashaNoz/Calendar
Support the Channel - https://www.paypal.me/codeandcreate
Udemy courses:
...
If you wanna create a real database you are gonna have to learn some sequel, if you wanna make a fake one, you can just make a json file that stores all the info, just go online and search "how to make a database"
Can i should start js
I would use js yeah
for all the interactive items on the sight, such as clicking on the calender, or adding elements
html and css will just make the shell of the website. the JS is all the interactive code, clicking on a button and a message popping up for example
I know web HTML and CSS that you tell to me this is not understandable to me
make it simple
HTML and CSS is all the pretty stuff on the website. This is how you make things
Html put pictures
css make picture look pretty
javascript make pictures move and do things by user interaction
its where you store all the information of the site. User login infromation like username and password.
to the database, which can be stored on a server, your local machine, it could really be stored anywhere, just a place that reads that infromation
just forget about the database for now
work on the javascript first
later do the database
when we get host our website then where the data goes of sign up
Some hard drive that is run on the server
Is bootstrap relevant in today's world
yeah it is, its a framework that helps you develop a website and make it easier
Can you use it
bootstrap or tailwind.css
bs
why taillwind not
Prefrence
ok
I havent really used it
And tailwind is not a ui kit
while boost strap is
some people prefer one over the other, it all depends
what is ui kit
A UI kit is a set of files that contains critical UI components like fonts, layered design files, icons, documentation, and HTML/CSS files. UI kits can be fairly simple with a few buttons and design components, or extremely robust with toggles that change fonts, colors, and shapes on the fly.
You CAN but you shouldent unless you know what you are doing
Some of the stuff in both can overlap causing problems later on
where you learn it
10% school, 90% google
you not watch any tutorial??
I did, on google, mostly read though
you understand by only reading????
yeah usually, and testing
I am using vs code is it good
yeah
what if I not use any framwork???
so why people use it
So make large scale development easier
Thats good! Its always fun to start learning new things, if you have any questions just use google
itll be your best friend
are you doing job
computer science, web and software development
how much time you take to frontend
is there any channel for django ?
hi everyone
im just new to the community
im 18 and Im interested in web development
I would appreciate any guides in this field, eg: what libraries i should know or which framework is better?
@tired shuttle what type of web dev do you want to do? frontend or backend
or full stack
back_end
ok
so thats exactly what i do
i would still learn basics of HTML, CSS, and JS (JS mostly as you can do backend with JS)
i recommend this roadmap
great👍
i personally use Rust and C# for backend dev. i dont use Python much anymore
i had heard that if u want to be a good back_end developer u should be familiar with HTML and CSS
why dont u?
like Rust and C# more
and C# is growing massive recently. it has an extremely large ecosystem
aha i thought there r some technichal reasons
well Rust is miles faster than python
and I choose it because it incorporates many low level concept which I am interested in
how long have u been programming?
and another question is that which framework is better for python?
and how long it will take to become a senior in this field?
FastAPI is growing in the Python field
i started programming with Scratch at 5, but I really got into it in 2020
nice
what about django? I have heard about it alot?
its very good also
but if you don't want everything given to you off the bat, and want to make stuff yourself, don't use it
it is batteries included
???
idk it depends
which programming language u know?
for now just python
then learn flask
for back-end
it is beginner friendly
if in future u need help related to flask, the message me personally
I will try my best to help you.
thanks for your guidance🙏
nice u r too friendly👍
🙂
how do i stop anything other than output to stop showing in terminal?
Hey there, I have a question about StreamingResponses in FastAPI. I'm passing a generator to a Streaming. The generator keeps getting data over a websocket. So does this work like a FIFO or does it poll for a limited duration to get the data from the generator? Cause I'm a bit confused on what happens if I don't send data over the websocket for a few minutes and then resume sending it.
Hello i need help with django,
i removed 2 models from the database and removed the migrations of them and now when i run migrations it shows like everything fine
but doesnt really add the models to the database and i cant access them in admin panel error: Relation..." " does not exist...
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('headers: ', har['log']['entries'][0]['request']['headers'])
Message: invalid argument: log type 'har' not found
ping me on reply pls
<ipython-input-9-7f7348bca851> in <module>
----> 1 f.objects.all()
~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py in get(self, instance, cls)
177 def get(self, instance, cls=None):
178 if instance is not None:
--> 179 raise AttributeError("Manager isn't accessible via %s instances" % cls.name)
180
181 if cls._meta.abstract:
AttributeError: Manager isn't accessible via Auctions instances
.......
.......
.......
I am trying to do f.objects.all() but getting this error
Looks like you are running object on an instance. You have to do it on a class.
you manually removed the models, and then removed the migration files?
if so, you may need to also remove them from the migrations table that django creates...
normally, if you created a migration that you actually do not want, you would reverse the migrations and then delete them or just create new migrations which remove the tables
There's a discrepancy between the value I have stored in the db and the value I get from fastapi.
Stored DB Value: 9339981860999169
https://cdn.discordapp.com/attachments/776184661902491678/957348807438393404/unknown.png
https://i.imgur.com/XTmofAt.png
As far as I can see, I don't modify the ID manually, but it seems to change..
# services.py
async def create_club(session: AsyncSession, club: ClubCreate):
new_club = Club(club.name, club.description)
session.add(new_club)
await session.flush()
new_club = await get_club(session, new_club.id) # HACK: Had to do this to fix the db issue.
return new_club
async def list_clubs(session: AsyncSession):
return (await session.execute(select(Club))).scalars().all()
async def delete_club(session: AsyncSession, club_id: int):
new_club = await get_club(session, club_id)
if new_club:
await session.delete(new_club)
await session.flush()
async def get_club(session: AsyncSession, club_id: int):
return (
await session.execute(
select(Club).
where(Club.id == club_id)
)
).scalars().first()
async def update_club(session: AsyncSession, club_id: int, club_update_payload: ClubUpdate):
await session.execute(
update(Club).
where(Club.id == club_id).
values(**club_update_payload.dict(exclude_unset=True, exclude_none=True, exclude_defaults=True))
)
await session.flush()
return await get_club(session, club_id)
# routes.py
@router.get("/", response_model=list[PartialClub])
async def list_clubs(session=Depends(get_session)):
return await services.list_clubs(session)
@router.post("/", response_model=Club, status_code=HTTPStatus.CREATED)
async def create_club(club: ClubCreate, session=Depends(get_session)):
club = await services.create_club(session, club)
return club
@router.get("/{club_id}", response_model=Club)
async def get_club(club_id: int, session=Depends(get_session)):
return await services.get_club(session, club_id)
@router.patch("/{club_id}/", response_model=Club)
async def modify_club(club_id: int, club_update_payload: ClubUpdate, session=Depends(get_session)):
print(club_id)
return await services.update_club(session, club_id, club_update_payload)
@router.delete("/{club_id}/", status_code=HTTPStatus.NO_CONTENT)
async def delete_club(club_id: int, session=Depends(get_session)):
await services.delete_club(session, club_id)
return Response(status_code=HTTPStatus.NO_CONTENT)
# models.py
class Club(Base):
__tablename__ = "clubs"
id = Column(BIGINT, nullable=False, primary_key=True, default=id_gen.create_id)
name = Column(String, nullable=False)
created_at = Column(DateTime, default=datetime.now)
description = Column(String)
money = Column(BIGINT, default=25000000)
def __init__(self, name: str, description: str):
self.name = name
self.description = description
hello, I want to learn about api in python flask
suggest me any good tutorial where i can learn API with flask, I saw many videos but they were not so in deep
You have to learn what REST APIs are first
the basic flask program IS a REST API
My image is in {{dd.image}}, I want to ask where do I give the value{{dd.iamge}} in
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />```
app.get("/"), which is essentially used in all flask beginner tutorials is a GET request at the index route
can u please tell me why we use def list or create in a rest framework if we have ListCreateView?
it allows us to be selective on which kinds of methods we allow, if we disallow methods we don't need faster we get better results
and with generics specifying can be useful like the listapiview is read-only and tis explicit
while the list create isn't
@vivid canopy hope that helps
thx bro)
no worries
what is the average python web dev's tech stack look like

or feel free to share your own too
Flask/Django(the most average)+django rest framework/FastAPI
Postgresql (DjangoORM or Sqlalchemy)
Redis/rabbitMQ
Docker
Nginx
Pytest
Gitlab CI
Linux (working with Ubuntu/Debian is enough)
Feel free to get acquainted with Alpine for docker images purposes though
U asked for python web dev stack

This would be already for person going to full stack road
Anyway.. React or Vue.js
React or Vue.js
Some sort of related state management system
SCSS
Not really, just used SCSS to impement latest project full of custom stuff.
I would use CSS framework for pet projects because I am not designer though
Hey all, I got a weird question and the FastAPI discord is dead
Alpine Linux is cool for docker. It is really small. 5mb base size
figma lets you export code too

i will note this down

I'm having a issue with a background task that I created. Its a simple function that goes in an infinite loop with a sleep and is created by asyncio_create_task. When I run this FastAPI instance under uvicorn everything is working fine and does what it needs to do. However, when I use gunicorn and pass in the UvicornWorker, I can see the task being created, but the function never executes. Any ideas?
do you think you will focus on web dev or move to another specialty in future or wait you said you were mostly backend/devops, right? i cant remember 
I will remain in web dev and concentrate on backend/DevOps
My future plans
- getting hands on fastapi and async related python ecosystem
- practicing golang
- learning tekton/argocd as kubernetes native gitlab CI alternative
- learning Kafka and building microservices architecture around it
- improving my code quality things to handle really big sized projects
- practicing with AWS
- learning secondary cloud infrastructure objects like Vault, Elastic search, mongodb and etc
- getting more exp with Postgresql, and wishing to try Flyway dB version control system
And I am certainly not going to improve my frontend or anything related to it.
Except may be a bit setting up testing stuff for that
I like infra more than front
I already tried Frontend with Vue.js, so I got the taste of it
It has some certain appeal in simplicity and relaxation, but it is not for me
i see
Front end sucks.
there is always need for more backend than frontend i feel like 
my background is in DS so it all is new to me 
It is good to know a bit of frontend for general education of web Deb
yeah im trying to learn as much as i can for this website project for my software engineering class rn
since it seems the other team members are unreliable 
like
they are all CS majors and im the only AI major
why am i the main developer 
honestly i will probs end up having to make this entire website by myself. already calling it 
but at least i will get to learn stuff
That is normal. Students are often immature in what they learn.
yeah i know but like...these are grad students so i expect some more level of maturity than undergrad 
but i guess it seems common in CS programs maybe

During uni one of other students made a hack with js to pass our computer network exams.
And shared to all other students
Tbh what he did still looks like magic to me
I did not even I am going to be web developer until I got first job
Hell, I did not know I would be even programmer until I got taste of first job
For the last one year and half I got certainty with my path and moving into one (two) directions
Backend+DevOps is a nice combo of my choice
Usually people just go backend, or just DevOps, or frontend, or full stack
My choice is just my personal quirck born out of need at the past job of handling everything alone
I started to work in a good company now... But I already got used to certain ownership of Backend and infra at a more intimate level
And it is just stacking well
i like DS work and i will explore if i like dev work too, especially this summer (SWD internship), so i may try to follow your path and find a good combination if possible
DS can make a combo with backend I think
Your future company will value your DS/ML much more if u could code it in not a shitty way
i know it can make a combo with DevOps. DS + DevOps =MLOps
Out of all web devs, backend guys learn the most of code quality stuff
yeah maybe can incorporate ML-type of features into software apps (i.e. recommender systems, etc.)
I suspect it is better to learn minimal viable backend first before diving into MlOps
Because it will give the basic instruments to operate during MlOps
DevOps stuff is meant to be started with person having already some background in other stuff? In Backend or in Ops?
yeah thats my take on it too. bc its a a big jump by itself.
Bwhahaha
Reading article for differences between DevOps and MLops
Checked the author name and nickname...
... My brother.
Anyone knows how can I interact with a source game server console with python in a website?
some sort of API
your brother wrote the article? 
Yeah
Conviniently he is experienced DevOps person which participated in all sort of public activity
It is long article written in my native language.
If to summarize his all words.
MlOps = machine learning with DevOps with difference in
- pipeline for MLops requires not just code as data input, but also data and parameters, and results in model and then release
- requires more hardware
- monitoring of the system has some sort of dynamically changeable specifics to what is monitored
Main thing for MLOps to automatize building of model and its training tuning.
That alone will free more time for ML specialist to work more on model.
ah that tracks with what ive heard
they even specific tools for it but i wont get into it in this channel 
since its OT
Sigh. What I learn now, he learned already three years ago
It looks impossible to catch up with him
He is pure DevOps though, while I am a hybrid between backend and DevOps. So at least in backend knowledge and general code quality stuff I should be able in theory to surpass him. Not guaranteed though
lol its okay. you dont have to compare yourself to him. everyone is on their own path 
Just a classic sibling rivalry ;)
can u gather input using the backend or would u need to take it using js and send to the python app?
you can for sure gather input using backend

