#web-development
2 messages Β· Page 40 of 1
guys, i have to iterate two difference elements in the same for loop
in jinja2
{% for application in applications %}
{{ user.acc_username }}'s {{ application.id }}<br>
{% endfor %}
i have iterate the application from this function route:
@app.route('/applicationlist')
@login_required
def applicationlist():
applications = Applications.query.filter_by(rate=0).all()
users = []
for app_ in applications:
user = User.query.filter_by(acc_id=app_.owner_id).first()
users.append(user)
return render_template('applications.html', title='Applications', applications=applications, users=users)
but i have to iterate users too, to print, for example: "John's application 12"
how can i do it?
@cloud path are the 2 variables username and application the same length?
yes the list is the same length, but i've solved! in this way:
return render_template('applications.html', title='Applications', appuser=zip(applications, users), applications=applications)
i've zipped the applications and users in one parameter
and in jinja i've done this loop:
{% for application, user in appuser %}
<a href="{{ url_for('appcheck', appcheck=application.id) }}">{{ application }} di {{ user.acc_username }}</a><br>
{% endfor %}```
and it works, thanks anyway ^^
thats the way I was going to tell you about π
ah nice haha ^^
@frigid egret try to check if ur server configuration is correct
Hi, I have a question that I strangely enough could not find any answer to by googling. With Flask, I can do redirect("") as in pass an empty string, that will redirect me to the same page that im on. Im using this for formvalidation. Instead of doing redirect(url_for("same route im on") I just pass an empty string. Is this documented anywhere?
Im doing the CS50's Web Programming with Python and JavaScript and it feels like cheating π
as long as ur doing alright
not related to the topic but im struggling on making my own language REEEEE
And if my validation is very simple, like as long as the value isnt empty I actually dont see any reason to use WTF
But hey, Ive been programming Python for less than 2 weeks so what do I know π
@native tide I am currently taking the same course, and I did it with WTForms, which in my opinion was more difficult, and took a lot more effort. But I learned much more
@tranquil robin I actually used WTF first but removed it, It felt like so much boilerplate for no gain since all you really need to check is if we are not trying to pass empty values in the forms.
@native tide you can try a mix of flask message flashing (https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/) to feedback the user, and just check for the length of the inputs using request and len(string).
Thats exactly how im doing it. Since all thats needed for any field is that they should not be empty im just having all required on all inputs, and then just checking if request.method == "POST", if values are empty flash and redirect
I dont have any issues with it, I just cannot find any documentation on that its ok to use redirect with empty string
if it works then great, cause you would not create a a functioning website that way in the first place
It just annoys me that I cant find anything about it π
just try it, if it works then ok, if not find another way π
It do work
then why are you looking for documentation?
I want to know why
π
Coming from a javascript background I so far find the python documentation to be complete crap
I am not knowledgeable enough to answer that, gl finding an answer though π
for me its the opposite π€£
Watching Corey Schafer's python tutorials on youtube has been awesome tho
I did the same, probably gonna watch his Django one for project 3 π
you can maybe find something here as well, https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
https://github.com/zedr/clean-code-python this one was really helpful to me
Why is it that you have to convert UTF-8 strs into bytes to send them to Django in Python3?
can some one check my question https://stackoverflow.com/questions/60017258/create-dynamic-flask-socketio-pages-based-on-n-json-files
@foggy quarry may I ask why are you creating this using socketio?
@tranquil robin well flask kinda simple, and i need js table constantly updating, and to practice i made a page for one .json file, but when i need logic for more, this when i stuck, is there a better technology for this?
from what I understand in your post is that:
- you have many files in you folder.
- you have Apple that is the main page (html and json)
- you have many different routes (Gala, Fuji ...etc) you want the main html to be like Apple but add things using (Gala.json and Fuji.json)
do you want to reach the different pages in this way:
-example.com/apples
-example.com/Gala
-example.com/fuji
...and so on?
@tranquil robin yes, and those pages must have a js table, that will constantly get updated, because the data in json files will change also, and i have n json files
the content must change live? or when you refresh the page?
@tranquil robin yes the end pages must be live, this is why i look for socket-io
I think you can just do it with Flask ( app.route(/<variable>) , flask jinja2 and javascript
quick question...do you need both minlength as a HTML attribute and an Angular minLength validator?
Django reltated question:
does TextField preserve formatting as in \n; \t and multiple spaces?
yes it does
guys, why the style doesn't change? (i'm using flask-bootstrap), this is the code:
Does anyone know how to setup a webhock for youtube live notification i mean not publishing videos but whenever a guys does live
...
{% block styles %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="{{ url_for('.static', filename='style.css') }}">
{% endblock %}
...
...
...
{% block navbar %}
<nav class="navbar navbar-default">
...
</nav>
{% endblock %}
--------------------CSS File in .static/style.css-----------------------
.navbar navbar-default {
background-color: black;
}
tried hard refresh?
what you currently have I think will try to select an HTML element named navbar-default which is a child of a navbar class.
mm ok but it still doesn't work :/
If you inspect the element in your browser, does it show that the style is there?
none
Your style is now ```css
.navbar.navbar-default {
background-color: black;
}
i think he means in the browser
I was just confirming the correct was made correctly
yes in the browser there is no custom style
What is your browser
chrome
click the sources tab
Not sure what that means π€
D: i try to search on google
you don't see any errors from your browser or flask regarding the stylesheet failing to load?
mm no, it doesn't seem to me
@cloud path i think its the extra "dot" in the folder static {{ url_for('.static', filename='style.css') }}
I dont think there should be a dot there
what does the directory structure of your flask program look like?
the static folder may need to be inside the app folder
you're welcome
glad you solved it π
^^
is .distinct() what you are looking for?
Maybe
I'll try that
Ajanvaraus.objects.order_by('aika').distinct(), shows only the non unique values.
I wanna show only unique values
It has some caveats with order_by which may apply to you https://docs.djangoproject.com/en/2.2/ref/models/querysets/#distinct
Now it gives error: DISTINCT ON fields is not supported by this database backend
Maybe it's not supported on sqlite3
Should it be?
Are you specifying an argument for distinct()?
the docs state that is only supported on pgsql
On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply.
hmm can't you just use distinct first and then order?
I'm assuming order_by is what's causing the issue here but you didn't explicitly confirm that
It returns non unique values for some reason
even without order_by?
yes
What do you consider to be a unique value?
cause distinct applies to the entire row
So I am making appointment app, so the Owner puts date and time what works for him and then customer comes and picks from the list of times what works for him and fills out his information. Once time is picked, you don't wanna let someone else to pick the same time, so I put OnetoOneField there. Now customer sees all the times the owner has setup and he needs to trial and error all of them to try which one is available. So I wanna sort out the once which are unique (Not taken)
Hopefully that makes sense
#models.py
class Aika(models.Model):
date = models.DateField()
time = models.TimeField()
class Ajanvaraus(models.Model):
aika = models.OneToOneField(Aika, unique=True, on_delete=models.CASCADE)
etunimi = models.CharField(max_length=150)
sukunimi = models.CharField(max_length=150)
email = models.EmailField()
puhelin = models.IntegerField()
viesti = models.TextField()```
.distinct will work, I am sure of that. I think my database is broken
I don't think it will
It sounds like what you need is a difference
As in, query all Aika and use difference() to exclude the times that are in Ajanvaraus
Not sure how to do that
Maybe just need a filter
is there like a official django forum where I can ask that? If there isn't I think I am gonna try to ask it in a StackOverFlow
Thank you for trying to help me π
How do i change user permissions in django using template tags
that is usually done in route code
how to i connect to be done when a button is clicked
Here's the docs
and returned stuff regarding prems in render functoin
Yes
could you link me to some example
Did you checkout the docs?
yeah, but i couldnt find an example of deleting or adding a custom permission
Do you wanna add permission to CBV or html template?
i want to add permission to a user using template tags
Like that only user with permission can see specific stuff?
yeah
so i just need to know how to add or remove custom user permission
Ok
{% if user.is_authenticated %}
is that what you need? Or can you explain what do you mean by custom user permission?
i created a permission called staff_member which allows you to view a specific page on
i also created a page the admin to change user permissions(basically whether or not a user can view that page )
I want to be able to change wheter or not a user can view that specific page
ok
so i need to know how to delete or add the permision to view that page
no i want to give a specific user permission
like user.has_perm(βfoo.add_barβ)
how do i do that on the click of a button
I think easiest way to add new permissions for user is to go to /admin and change them from there
Or is that what you want?
yeah i wanted to give that a html view
hmm
I don't know if you can even do that in django. Maybe you can, but I can't find it. If you find out please let me know.
Maybe do cbv and work from there
hi im new to python development so i wwas just wondering when u use flask or django do u need to integrate it wiht the wsgi ??
AFAIK django does that for you
Question regarding Django:
Before I go and build it myself: Is there a convenient way to use the prebuild infrastructure used in the admin the section to let users edit models/objects?
what about flask ??
seems pretty straightforward to me.
I personally use gunicorn as I am familiar with nginx and it is pretty easy to deploy for my server.
oh i wasnt sure if i actually had to implement wsgi for flask on it
thnx heaps that helped a lot
what about flask ??
@grim cedar uwsgi is integrated already in both flask and django
oh i ithought i had to integrate it myself
so @vagrant adder if i make a reverse proxy (nginx ), i dont have to implement another wsgi for that proxy server??
nope
although actual web servers are recommended to run websites, not dev servers
so instead of python run.py, gunicorn run:app -b 0.0.0.0:50000 will run flask in prod mode
ohh sweet!! than heaps @vagrant adder
cheers
hi again!! just out of curiostiy are there any reasons that you would create ur own wsgi server ?? few eg?
Because it is the recommended way to run wsgi apps
An apache or nginx is a lot more suited to take high amounts of connections than a python script
@grim cedar
If you have a very high volume you also need to think about load balancing
e.g. with haProxy
i meant wsgi servers ??
wsgi servers run wsgi apps, same difference
The built-in methods like Werkzeug are really only for development and testing
wait ?? wsgi is only for running python codes on web server isnt it ?
Yes
But Ruby has something similar, called Rack
But WSGI does not equal a python program, it is IMHO a subset
i researched on it , when i started programming i used java serveletAPI
so wsgi is pretty much servletAPI for python isnt it ?
yes
And in Java you'd use tomcat, in Python you can use any webserver that supports WSGI
Why?
contradicting myself haha
but yea i think i got better understanding now from waht u explained me thnx buddy
n htnx for ur time
no problemo π
thnx^
Question regarding Django:
Before I go and build it myself: Is there a convenient way to use the prebuild infrastructure used in the admin section to let users edit models/objects?
Even finding the templates would be totally fine with me but I see no reason not to reuse stuff
@grim cedar you would build your own wsgi server only if you are unable to use integrated dev server, can't download any web servers from internet or for a personal project :p
i don't see the purpose in building a webserver from scratch unless you are told to
@vagrant adder As soon as the stuff is out of production, you really sholdn't use the integrated servers anymore
they are not safe enough and can't handle any significant load
i know, i use gunicorn for anything other than local development
Yeah, but gunicorn is an "app server'
it is highly recommended to have a reverse proxy like nginX in front of it
of course
Just going off what you said to sexpistol
can't download any web servers from internet
I personally have gunicorn running my django in a docker container and nginx serves as reverse proxy to the container. seems to be the simplest solution imo
I use apache with mod_wsgi on my pi
just as simple
all depends on what you need
but these things are really simple to set up
well, for me...
pi is not enough for my purposes but yeah it is atleast simple to learn
my current flask project revolves around the PI π
standalone internet radio
with a touchscreen
I will use a PI in the project im currently working on as that involves people from a company editing records, but the whole thing just stays in the internal network
so limited amount of users; no previous hardware; database on a different partition(not the sd card of the pi) and the pi is ideally suited for the purpose
and it isnt exactly highly important data.
Sounds good
@vagrant adder i was just curious if it actually would help me gain better understading of internal stuff between wsgi server and web server
so im confused about gunicorn workers
y is there async worker and then asyncio worker when it pretty much does same thing
??
so far i get that async is used for coroutines and handling long request and the threading is done is program level instead of os level so it creates blocking programs, does that mean async io worker deals with the maintaining threads ??
to solve that blocking program problem??
is that the only diff ?
i think i got what it does now lol... sad life...
Hi guys I'm building something in Bokeh and it needs a small amount of Javascript. I've adapted what I can from other examples but am stuck on getting the syntax right for a basic nested IF statement. I asked in help and @sturdy sapphire suggested I ask here... Here's what I'm working with:
for (var i = 0; i < source.get_length(); i++){
if (source.data['Periodno'][i] == Periodsl.value &&
source.data['Sectors Scheduled'][i] >= SchedSlider.value[0] &&
source.data['Sectors Scheduled'][i] <= SchedSlider.value[1] &&
checkbox_group.active.map(i=>checkbox_group.labels[i]).includes(source.data['Main_Airline'][i]) &&
arriving_select.value.includes(source.data['Arriving_short'][i]) &&
departing_select.value.includes(source.data['Departing_short'][i])
){ indices.push(true);
} else {indices.push(false);}}return indices;```
This works fine for my purposes except it's really slow and laggy, so I'm trying to get the first condition `source.data['Periodno'][i] == Periodsl.value` to run and if this isn't true then push false for that indices. Could someone please help me understand the syntax with JS's weird {}[]() brackets??
can someone help me with django(PM me)
hi
I've got a Django Q which I'm about to type.... π
I'm used to using htpasswd in PHP projects, but I'm using a Django app for the first time and I'm typing runserver, so I'm presuming I'm not using Apache, and therefore I can't use htpasswd in .htacesss
Is that correct?
When running the test server it doesn't use Apache
But you could deploy your django app with apache server
Hey @fast narwhal!
It looks like you tried to attach a file type that we do not allow. We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg.
Feel free to ask in #community-meta if you think this is a mistake.
# views.py
@user_passes_test(lambda user: user.is_superuser)
def userpermissions(request):
selected_name = None
selected_perm = None
all_users = User.objects.all()
if request.method == 'POST':
selected_name = request.POST.get('dropdownusers')
selected_perm = request.POST.get('dropdownpermissions')
context = {'all_users': all_users,
'selected_name': selected_name,
'selected_perm': selected_perm
}
return render(request, 'scripteditor/userpermissions.html', context)
# mytags.py
from django import template
from django.contrib.auth.models import Permission
register = template.Library()
@register.filter()
def check_permission(user, permission):
if user.user_permissions.filter(codename = permission).exists():
return True
return False
@register.simple_tag
def addPermission(user):
permission = Permission.objects.get(
codename='staff_member', content_type__app_label='scripteditor')
user.user_permissions.add(permission)
@register.simple_tag
def removePermission(user):
user.user_permissions.clear()
the selected_perm is not printing anything(Ping me if u can help)
Under what situations would you choose to host on a traditional server vs a container vs a cloud base system?
guys
i've a single name field in the database that is formed by
name_surname
is there a way to show it as 'name surname' without the underscore, in a template rendered with flask?
cheers
if anyone can help me with django
!ask
Asking good questions will yield a much higher chance of a quick response:
β’ Don't ask to ask your question, just go ahead and tell us your problem.
β’ Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
β’ Try to solve the problem on your own first, we're not going to write code for you.
β’ Show us the code you've tried and any errors or unexpected results it's giving.
β’ Be patient while we're helping you.
You can find a much more detailed explanation on our website.
Django:
I am currently looking for django documentation of receiving and processing user input. Specifically I want to learn how to create fields that take user input then validate said input after which I save it to my database
Specifically I am unsure about when to do my validation
Also does the str of a model class need to be unique?
def __str__(self):
return self.identifying_str
i think validation is done both in server side or front end
or u can choose to have it on ur nginx server too
better if u do in both
U need to create forms to take user input, then u need to use a view to retrieve the data @jaunty quiver
Forms generally have built in validation but you can add ur own validation too
If you want to save it to the database, then I'd say use a modelform
Or you can just have a form and add data into the database using sql commands
anyway, does anyone familiar with Django REST Framework know what the idiomatic way to send a file in the response is?
I have a route set up that takes an (image) file, runs some deep learning on it and returns a numpy array representing an image
I probably want to convert that image to a png or something and send it back in the response
Thanks
hey guys, here is problem i am facing. So my backend is built on Django. and my frontend is built on React. Now tricky part is django is working on example.com and my frontend is working on example-app.com i am using oauth-toolkit for authentication. So when user is not logged in i redirect user to example.com/accounts/login which is using usual django's authentication which creates a cookie for logged in users. And i am sending graphql request to backend from react app(frontend). As far as i understand browser will append cookie generated from example.com to every request from example-app.com right? but for my case it is not. Can any one explain this ?
It will append the cookies to a subdomain (login.example.com for example), but not to another domain
Hi I wanna make a simple blog about me as a side project... Should I use flask or Django... which is easy to learn and make a blog from....
flask is easier to learn but django would be easer to make the blog in.
i think it would be faster to learn flask to make the blog, then if you where to do the same with django
I do not know if i would just say that flask is easier to learn, it is less complex though.
@solar hatch
guys, why the items in the ul navbar-right, are anyway on the left-side in the navbar(with flask-bootstrap)?
{% block navbar %}
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a id="item-nav" href="{{ url_for('index') }}">Dashboard</a></li>
<li><a id="item-nav" href="{{ url_for('createchar') }}">Crea personaggio</a></li>
{% if not current_user.is_anonymous %}
<li><a id="item-nav" href="{{ url_for('applicationlist') }}">Applications</a></li>
<li><a id="item-nav" href="{{ url_for('appstore') }}">Storico applications</a></li>
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
{% if current_user.is_anonymous %}
<li><a id="item-nav" href="{{ url_for('login') }}">Login</a></li>
<li><a id="item-nav" href="{{ url_for('register') }}">Registrati</a></li>
{% else %}
<li><a id="item-nav" href="{{ url_for('user', username=current_user.acc_username) }}">Profilo</a></li>
<li><a id="item-nav" href="{{ url_for('logout') }}">Logout</a></li>
{% endif %}
</ul>
</div>
</div>
</div>
</nav>
{% endblock %}
is it possible to send a file in a response in Django?
You can redirect the user to the download
should I use flash() or just pass in an error like
error = None
if something:
error = 'some error'
else:
error = 'some other error'
return render_template('index.html', form=form, error=error)
if you are using bootstrap it's better to flash
guys why the img tag doesn't work?
am i wrong something in the tag?
i've passed it in this way
1: '<img src="https://wiki.sa-mp.com/wroot/images2/2/2e/Skin_1.png">'
}
...
return render_template('character.html', title=char.char_name, char=char, skin=skins[char.char_skin])
ok solved
with Markup(<img....)
i used some icons from font awesome and linked to ```<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
i wanna download the lib locally how do i get it?
i downloaded the library from the website and linked to ```<link rel="stylesheet" href="libs\fontawesome-free-5.12.0-web\css\fontawesome.min.css">
it didn't work
nvm got it
Hey everyone, I keep getting stuck with my Django projects. Using a django app inside a django project feels like i'm overengineering things. I have some project ideas that I want to build API's for with authentication and some data structures, accessible by different clients.
Using apps within a Django project is a pretty normal workflow. You shouldn't be scared to use them and they could serve as a nice separation of your code if you have a natural separation into subparts.
I tried to do that but the value of select_name turns to None when it reaches the nested if statement
# views.py
@user_passes_test(lambda user: user.is_superuser)
def userpermissions(request):
selected_name = request.POST.get('dropdownusers')
selected_perm = request.POST.get('dropdownpermissions')
all_users = User.objects.all()
if request.method == 'POST':
selected_name = request.POST.get('dropdownusers')
selected_perm = request.POST.get('dropdownpermissions')
if selected_perm == "Not Authorized":
selected_name.user_permissions.clear()
elif selected_perm == "Staff":
permission = Permission.objects.get(
codename='staff_member', content_type__app_label='scripteditor')
selected_name.user_permissions.add(permission)
context = {'all_users': all_users,
'selected_name': selected_name,
}
@vestal hound presumably just HttpResponse(png_converted_image, content_type="image/png")
and png_converted_image would be a file object?
Hey guys Does anyone know how to use google API with Django? I already have an API Key but don't know how to use it with my django website, do i need to learn django rest framework to integrate it? Thanks!
https://pypi.org/project/django-google-api/
@charred iron
Is that what you were looking for?
I was just wondering if anyone had any advice on wether to use Django/ Flask or Angular/ React/ Vue for basic dashboard project?
guys is there a keyword in the flask form validators for accept only numbers from x to y? (ex. number from 1 to 100)
ok solved
with numberrange
Hi! Can anyone give me the advise how to add unique ID to <div> based on available objects in database? I created function in context_processors which return dict {'page_id_1':'page_id_1', 'page_id_2':'page_id_2'...and so on}. How can I add a unique id to each page in my project?
same solution is in Wordpress where each subpage has a unique ID so it's easy to style this with css
@native tide I am unclear about what you want to do. If you want to include a variable from your context in your css class that should not be an issue
{% for article in article_list %}
<div class="{{ article.cssClass }}">{{ article.title }}</div>
{% endfor %}
afaik that should work given that you configured your models and css classes correctly
and I need in every unique subpage template something like that: <body id="page-id-{{unique_subpage.id}}">
so for loop is not gonna work
afaik in django each object by default has unique ID so it should work
You can pass the pk of your object in the url and then pass your object based on id there. It should also be no issue to use that pk to determine which template to use
and the passing of the css class via model is absolutely possible without any loops
just pass the object itself instead of the list
but this is working: <body id="page-id-{{unique_subpage.title}}"> because I have field title , so why {{unique_subpage.id}} won't ?
can you print the id from your before rendering?
I I know I use the latter one in my project. (utilizing the pk)
{% extends 'base.html' %}
{% block content %}
<h1>Bacon Ipsum:</h1>
<form class="form">
<button class="button">Lorem Ipsum</button>
</form>
<ul>
{% for foo in fooList %}
<a href="{% url 'myApp:foo' foo.id %}"><li>{{ foo.bar }}</li> </a>
{% endfor %}
</ul>
<form class="form">
<button class="button">lorem ipsum</button>
</form>
{% endblock %}
This links correctly to the desired url (foo namespace/pk) I dont know what you are doing wrong.
as long as you pass the entire object it should have an id
you are doing this through urls because you want this in url, I just need ID in class name - so this is a problem π
mayby I need to create a field with ID
this was meant as a general example of passing the id to the template working
nope you shouldnt have to
how are you passing your context?
maybe it gets lost there?
I have to go now, but thanks for help . I will come back later
def fooOverview(request):
fooList = Foo.objects.all()
context = {'fooList': fooList}
return render(request, 'foo/fooOverview.html', context)
this is my most minimalistic approach of passing the objects.
Now onto my own question:
Is there a way to create dynamic forms using django?
Example
lets say I have the model Article looking like following:
class Article(models.Model):
title = models.CharField(maxlength=30)
scientific = models.BooleanField()
doi = models.CharField(maxlength=30, blank=True)
Now I want the user to be able to create new articles. As long as scientific is False the form for doi isnt supposed to show up, but when it gets checked the form should show up and now be required.
any good source to learn Django Template?
django themselves have written some really well written and comprehensive documentation about it that i'd normally be using as a go-to.
https://docs.djangoproject.com/en/3.0/ref/templates/language/
so ive made a nice web form: https://xenon.bss.design/ESMB.html
but I dont know how to do the Flask part
Its kinda a lot to ask but could someone possibly throw together an example of one of each of the types of form inputs
on my site
(checkbox, text entry, drop down select, number entry)
I can send you my HTML code or you can just check the source code on the site
I followed Miguel Grinberg's flask mega tutorial, web form is 3rd section.
but im not using a template
using already created html code
do I just add in the extra parts?
Sry I don't know what u mean. I'm a bit of a noob, so can't be of much help. If you're using flask, you can use jinja2 template engine in your html files afaik. When I was in your situation, I used wtforms(converted my already written html to it), since all the tutorials seemed to use it. I didn't really want to because it's annoying to learn new syntax, but I wanted csrf protection which is built in to wtforms, and seemed easier just to go with it.
Hello!
does anyone here know what this error means?
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqlite3
Using flask-SQLAlchemy
searching for the error, it seems maybe ur typing the string wrong in create_engine?
hi what are the best data visualization frameworks in python (in web development) to start with for begineer ?
/home/alexander/Documents/ESMBflask/bin/python /home/alexander/Downloads/microblog-0.3/app/init.py
Process finished with exit code 0
Running the microblog tutorial script
ive tripple checked everything but it doesnt work
it just exits
no errors
problem with heroku or python: saves previous pyplot even if i "git push heroku " with no image file. and create a new but different image file with the same name. it shows the previous image?
os.remove is not deleting file in flask
@jaunty quiver I solved problem with this ID. I had to convert id to string, so instead {{subpage.id}} I added custom filter and it's working now {{subpage.id|tostring}}
Hi, guys, i've an automap to work with an existing database in my app project. When i start it on my pc with flask run command, it works fine, and it saves data on the database. Now i'm trying to put my app on a debian server, when i run the app with gunicorn, it return me this error:
sqlalchemy.exc.ArgumentError: Mapper mapped class Applications->applications could not assemble any primary key columns for mapped table 'applications'.
This is my models.py:
from flask_login import UserMixin
from sqlalchemy import Column, Date, Integer, String, create_engine
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.automap import automap_base
Base = automap_base()
class User(UserMixin, Base, db.Model):
__tablename__ = "accounts"
def __repr__(self):
return "User {}".format(self.acc_username)
def get_id(self):
return (self.acc_id)
class Char(Base, db.Model):
__tablename__ = "characters"
def __repr__(self):
return self.char_name.replace('_',' ')
class Applications(Base, db.Model):
__tablename__="applications"
def __repr__(self):
return "Application ".format(self.id)
Base.prepare(db.engine, reflect=True)
@login.user_loader
def load_user(id):
return User.query.get(int(id))
I've already tried to specify the primary key column into the tables, but after this, it does not find the other parameters, so it is as if it wanted me to write them one by one, as if the automap from the existing database was not working
Name your class Application
done
now it return me this error:
sqlalchemy.exc.ArgumentError: Mapper mapped class User->accounts could not assemble any primary key columns for mapped table 'accounts'
i have to name "Account"?
instead of User
done but still the same error
What does your database look like
Show the the table definiton for accounts
Sqlalchemy requires primary key id column to make relationships
when i declare primary key into models it returns error for the others parameters, this is the table:
solved
it wasn't a problem of sqlalchemy automap
but of the database url
thanks anyway
Hi, I am looking to create a headless webapp, where should I start from?
Iv ltierally created db with flask and sqlalchemy 100 times , right now my models.py cant import db from init
i cant udnerstand why
created new virtualenv with just__init__ and models
im i blind or retarded ? i did this so many times it never happened before
Its some circular import shit but i just cant seem to understand
Hi guys, I am running into an issue here.
from bs4 import BeautifulSoup
markup = '<ul><li>Fixed an exploit with refertilizer and the anti-mesh system which allowed for the destruction of enemy bases on <abbr title="Players Vs Environment">PvE</abbr></li><li>"Zehbi"</li></ul>'
html = BeautifulSoup(markup)
html.abbr.unwrap()
for tag in html.find_all():
print(f"{tag.string}")
When running this, my output looks like:
None
None
"Zehbi"```
Is there any explanation for even after removing the abbr tag, the text still doesn't get recognised by the `tag.string`?
Weirdly enough, if I convert the beautifulsoup object to a string, import it again, it does give me the ouput I am expecting.
code:
from bs4 import BeautifulSoup
markup = '<ul><li>Fixed an exploit with refertilizer and the anti-mesh system which allowed for the destruction of enemy bases on <abbr title="Players Vs Environment">PvE</abbr></li><li>"Zehbi"</li></ul>'
html = BeautifulSoup(markup)
html.abbr.unwrap()
for tag in html.find_all():
print(f"{tag.string}")
html2 = BeautifulSoup(str(html))
for tag in html2.find_all():
print(f"{tag.string}")
Output:
None
Fixed an exploit with refertilizer and the anti-mesh system which allowed for the destruction of enemy bases on PvE
"Zehbi"```
html = BeautifulSoup(markup.content, 'lxml') ?
What would the .content do?
It wouldnt do nthing rn because bs dont work with str as far as i know
what are you trying to do i kinda dont get it
Okay so I got this part of the html file, which I call markup. I load this markup into a bs object. After that I am trying to unwrap the abbr tag, so the full tag gets changed to '<ul><li>Fixed an exploit with refertilizer and the anti-mesh system which allowed for the destruction of enemy bases on PvE</li><li>"Zehbi"</li></ul>'. But once I try getting the string of it with tag.string, I get none.
Also, according to the docs, strings are accepted
Everytime I edit the css of my flask project i need to refresh and remove the cache (Ctrl + Shift + R) to make the css change. Anyway so I don't need to do that?
@hollow glacier try with TEMPLATES_AUTO_RELOAD = True
app config?
yeah
not sure will it work i had somethiing similar while ago i just got used to reloading
doesn't work :/
@exotic sand you just need the string from this without the tags?
Basically
But that's not the issue I am trying to solve here. Normally I would have a full website loaded here, so converting the entire website to a string is far from optimal
for tag in html.find_all(??):
print(f"{tag.string}")
then u need to find what
etc
for tag in html.find_all('div', {'class' : 'classname'):
print(f"{tag.string}")
Yes and how is that going to help you to get specific text from web site if you find all html elements
I don't think you understand me here. As I already mentioned, this is not the problem. The problem is that I have to re-import the website in order for .string to work
All I am asking is why this is happening
I am heading out i dont know what you mean with reimporting website
i dont see that u are using request on any url
here i can give a snippet of some scraping i did few days ago its messy but u see the request and other things if that is what bothers you cause u just use beautifulsoup on markup string i dont see you doing request on webpage
inside url = 'http::///ww.what.com' etc
Does anyone know, perhaps if the amount of json text u output, as server/website (api) the longer it takes for that to be received? i use an api where the time for the request to take is EXACTLY 1 second, i am guessing this is predetermined, however is speed influenced by the amount of returned values, if so if you'd return say 100 dictionaries which takes 10 seconds and then u change it up to 10 dictionaries and then it takes 1 second or is that just bs and is it all wifi related? (@ me <3)
@native tide is the request is longer in length, the transmission takes longer yeah
But is that in ratio, as proposed? Is it also possible to limit the minimum time to respond as a server, for example you set the minimum time to respond 1 second, so that it always takes atleast 1 second to receive the signal.
For some reason I am getting Exactly 1 second. With wired internet.
You can set a maximum request length
Do you want to limit the respond time on the server or on the client?
Well βlimitβ, more a minimum set time that it will take
Everything in ratio, will go faster in a x percentage from the original?
An almost perfect ratio yeah, the headers have the same length no matter how long is the body
I don't get why do you want to set a minimum time
You can simply use a timestamp and only process the value after one second
I am not sure why you brought up headers and body, since its an API return aka json data aka plain text.
Minimum respond time could be useful to avoid overload. So if 10k users would eg call the API link 100 times in a loop in a row, this would drastically increase server load if not make it more vunerable for Ddos attacks/(Unwanted) overload on the servers
Extra required energy, you name it...
The json data is the request body, and you have some headers for sure
Would you Say it mattered a lot to try to decrease your server output amount or is it not βworthβ the βdoingβ like, the diffrence would only be miliseconds, thus not that drastic
Yeah
Anyway, delaying the processing time by one second isnt the way to go, since you'd still process the same amount of requests at the same time, just one second after it was requested
The good way of preventing request spamming is to use rate limits
Yes but rate limits wouldnt matter in this case, because 10k request in an hour wouldnt matter if u loop it 100 times with Unlimited time
Nonetheless. Its 1 second Exactly, iβve tested it and i am quite confused by it, because i am not aware of any limitations and i am on a wire connection, then I would atleast expect to have some fluctuations within the response time?
I cant seem to get over this circular import for 5 hours now ill end up with nervous breakdown xD
Bootstrap 3 or 4?
I am currently learning django, and I'm making my first form. Is there a way to have the values of a ChoiceField change whenever another ChoiceField changes ?
also, is there a way to retrieve the current value of a ChoiceField from within a Form
Is there ayone working with flask to help me out i literally been spending 6 hours now trying to figure out why i cant get my models to work , did it dozen of times now im having some circular import it doesnt work with 3 basics files in folders...
@shell pewter use ajax for that
I have a web-dev question, not directly python related but I plan to host it with flask so....
I'm thinking of using react as my frontend framework for my flask site but I like the widgets and styles of Framework7 but on the other hand, I haven't learned either yet. My thought is that react will let me build the infrastructure on the frontend, and then I can use framework7 for the widgets themselves and use some style rules and such to show the iOS widgets on iOS, Material widgets on Android, and the Desktop widgets on everything else. And I want to make the site responsive too. I know it's a lot of work but It's for my portfolio. Is this compatable or would React and Framework7 conflict with each other?
I would not recommend using both but if you want to sure. The github link has something about framework7-react https://github.com/bencompton/framework7-react
Thank you
Hi! I have 2 problems with BeautifulSoup when using .prettify(). First - it's switching <img /> to <img> some other content </img> . Second - each <strong> tag in in new line. Can I somehow change those behavior ?
does anyone have a link to some good django cheat sheet?
how do i float:right an navbar item in bootstrap?
i tried float-right,navbar-right
nothing works
bootstrap4
@tranquil robin i've seen that , doesn't help
Django
How can I add the default static files responsible for the django admin to my static path?
Currently I have the isssue that nginx tries to serve them but cant; leading to not only the css being broken but also various registered models being broken
python manage.py collectstatic seems to have pulled it but it is not applied in the server itself
2020/02/06 22:09:47 [error] 6#6: *57 open() "/home/foo-app/web/staticfiles/admin/js/prepopulate_init.js" failed (2: No such file or directory), client: exampleclientIP, server: , request: "GET /staticfiles/admin/js/prepopulate_init.js HTTP/1.1", host: "example.com", referrer: "http://example.com/admin/articles/article/add/"
But looking at the directory the file exists there
Maybe nginx needs access to that directory?
I found the Issue:
nginx is trying to provide the staticfiles but due to being in another container it has no access to them and then 404s
shouldnt gunicorn do that job of collecting and serving the staticfiles?
appparently i am just full force stupid and used the wrong paths
Hello everyone,
I am about to finish my Flask course and I stuck on the last chapter related to creation of APIs
My application is designed in a way that routes are defined in a file called app/routes.py.
But in here the author has defined it in a completely different manner in initialization file called app/init.py:
from flask import Flask
from config import Config
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
from app.api import bp as api_bp
app.register_blueprint(api_bp, url_prefix='/api')
When I request localhost:5000/api/users/1
I get a 404 error, it happens for all other numbers (user IDs) that I have requested
My API blueprint:
from flask import Blueprint
bp = Blueprint('api', __name__)
from app.api import users, errors, tokens
. I have code reviewed many times and still canβt find a solution
. I have tried debugging but there is no bug, the application is too large so I review with my eyes and still I cannot find anything
I donβt know but I am sure there must be a way that other devs find such bugs :/
Any help?
http://prntscr.com/qymhrh
Config:
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = "B\xb2?.\xdf\x9f\xa7m\xf8\x8a%,\xf7\xc4\xfa\x91"
DB_NAME = "production-db"
DB_USERNAME = "admin"
DB_PASSWORD = "example"
FILE_UPLOADS = "static/files"
SESSION_COOKIE_SECURE = True
class ProductionConfig(Config):
pass
class DevelopmentConfig(Config):
DEBUG = True
DB_NAME = "development-db"
DB_USERNAME = "admin"
DB_PASSWORD = "example"
FILE_UPLOADS = "static/files"
SESSION_COOKIE_SECURE = False
class TestingConfig(Config):
TESTING = True
DB_NAME = "development-db"
DB_USERNAME = "admin"
DB_PASSWORD = "example"
SESSION_COOKIE_SECURE = False
from flask import *
from werkzeug.utils import secure_filename
import random, string, os
import requests
import hashlib
import json
app = Flask(__name__)
app.config.from_object("config.DevelopmentConfig")
extensions = ["png", "jpg", "mp4", "txt", "gif", "rar", "zip", "ico", "log"]
def allowed(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in extensions
def random_string(x):
return ''.join(random.choices(string.ascii_letters + string.digits, k=x))
@app.route("/", methods=['POST', 'GET'])
def upload():
if request.method == 'POST':
if "uploaded_file" in request.files:
file = request.files["uploaded_file"]
if file.filename == "":
return "Empty filename"
if allowed(file.filename):
filename = random_string(8)# + "." + file.filename.rsplit(".", 1)[1]
print(filename)
file.save(os.path.join("static","files", secure_filename(filename.strip())))
return redirect(request.url)
else:
return redirect(request.url)
return render_template("upload.html")
@app.route("/<string:file_name>", methods=["GET", "POST"])
def download(file_name):
if request.method == "POST":
print(file_name)
if True:
try:
print(os.path.join("static","files", file_name.strip()))
return send_from_directory(os.path.join("static","files"), filename=file_name)
except FileNotFoundError:
abort(404)
return "404 File not found"
if request.method == "GET":
return render_template("download.html")
#api
if __name__ == '__main__':
app.run()
app.add_url_rule('/favicon.ico',
redirect_to=url_for('static', filename='favicon.ico'))
Download.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
<button onclick="downloadFile()">Download File</button>
</body>
</html>
<script type="application/javascript">
function downloadFile(){
$.ajax({
url: window.location.href,
type: "post",
data: localStorage.getItem("auth_key"),
success: function () {
return ""
}
});
}
</script>
I want that the user can download the file i think its lacking at the send_from_directory part
when the function in flask is called i am getting an 200response
When creating a database, is it better to have many simple tables, or fewer tables that are a bit more complex?
It depends on the queries, usually simpler tables allow queries run faster. Also, depends a lot in the memory management of the database.
Check for functional dependencies.
ALSO, normalised tables (simpler ones) are prone to need more complex queries than complex tables.
the reqs come in handy in these situations.
π
Howdy Y'all. I am on my path to learn django. My first obstacle is that when I try to 'python manage.py migrate' it throws me a ModuleNotFoundError
I have two folders, one created with django-admin createproject and the other with django-admin createapp
where is the folder created with createapp located?
the file structure is the following:
chadrock
|βchadrock_app
|βchadrock_service
Where the chadrock_app was created via createapp
check if you added a "," in the installed apps in settings.py
here my installed apps:
'''
INSTALLED_APPS = [
'chadrock_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]'''
Indeed, I checked in SO someguy was missing a comma
But have not found yet why the migration is not identifying my modules. I'll create another app and try to migrate
Need help on defining GraphQL query
hello there
is there someone who could give me a hand with a django multi-table inheritance error?
@rustic pebble are you using graphene?
yes
im working with that, if you need help maybe i could gie you some
wats the question?
I am having huge trouble creating the request
ive adapted this example
I am not really familiar with graphene and it is my first project
iam lost as hell
this gh link is YOUR project?
no its an example
ok
i have copied and changed
what are your query, what are youre request and what the beahevior your expecting
yup
this is it:
Hmm im seeing that youre using an SQL alchemy, i have never worked with this, but anyway, i guess i should write a resolver methoid that proccess the query and returns the serialized object
like this, wait a minute while i write an example
class Query(graphene.ObjectType):
foo = graphene.String()
def resolve_foo(self, info, **kwargs):
return "hello"
just looking at ur schema looks like and user managig query for now
but queries need an resolver method
I am not rly familiar with the library thats why i have only a small idea of what is happening
I am basically trying to create a server to bridge a UI client environment I am making on .NET core and backend using flask
And I am having trouble connecting with the GraphQL
I am targetting to scale it a lot and I have seen that RestApi struggles to maintain after some time
if you, want for example write query that returns the power of 2 on a given user filer input you coul write something like this
class Query(graphene.ObjectType):
power_two = graphene.Int(value=graphene.Int())
def resolve_power_two(self, info, **kwargs):
value = kwargs.get('value', 0)
return value ** 2
or something like this
i got that
the ideia is that for each query you want you have to define a return type, like int, string or a self designed object type. and resolve it with the resolver method tha MUST initiate with resolve_ followed by the query name, in this case power_two wich results on resolve_power_two wich must receive an self for the class, and info that contains http variables of the request and the **kwargs tha is the user filter sinput
quick note, werkzeug 1.0.0 that released this morning CET is broken, shits itself on docker-compose
inside the resolver you do the database operations and returns the specified type
last stable version is 0.16.1
maybe you want to define a self designed graphql object with a graphene.ObjectType
like this
class Foo(graphene.ObjectType):
my_int_variable = graphene,Int()
class Query(graphene.ObjectType):
list_all_foos = graphene.Field(Foo)
def resolve_list_all_foos(self, info, **kwargs):
return Foo(my_int_variable=10)
i wont even pretend to understand this, i guess ill have to read docs more
the ideia is that you have to define a resolver method that returns exactly the type that specified on query attribute you want
i am so bad
on the beginnig ive got lost too
but with some pravtice you will understand
just follow that how to graphql tutorial some times
I have this huge project planned out
at your service
I have been trying to make an api server for around 12 hours, finally made and now I cant use it
bloody great
is an awesome rest framework
It seems very precise and direct
I am making a massive social platform
And I wanted something direct
im workin on a project thats similar to a social network latform with the graphqp backend
if you want to take a look
maybe you can have some light on your ideas
Thanks a ton! I will ping you if I need anything
π
π
@mellow briar I have finally made a correct request but i am getting more of a python erro
error
that cannot be explained
which error?
class AddUser(graphene.Mutation):
user = graphene.Field(lambda: Users, description='User created by this mutation')
class Arguments:
input = AddUserInput(required=True)
def mutate(selfs, info, input):
data = utils.input_to_dictionary(input)
data['created'] = datetime.utcnow()
data['edited'] = datetime.utcnow()
user = ModelUsers(**data)
session.add(user)
session.commit()
return AddUser(user=user)
Basically utils.input_to_dictionary(input) is a function i have made in another file which i have imported
I get this error
graphql.error.located_error.GraphQLLocatedError: 'created' is an invalid keyword argument for ModelUsers
Which I am not rly sure what it refers to
are you using django?
flask
does it make sense
no my model doesnot
from database.base import Base
from sqlalchemy import Column, Integer, String
class ModelUsers(Base):
__tablename__ = 'users'
id = Column('id', Integer, primary_key=True, doc='User ID')
name = Column('name', String, doc='Name of the user')
username = Column('username', String, doc='Username of the user')
#hashed password TODO create hash function
password = Column('password', String, doc='Password of the user')
thats the problem, you are giving the non existing field to the model
maybe you should try adding the field to the model, or modifying the data dictionary key
from graphql_relay.node.node import from_global_id
def input_to_dictionary(input):
"""Method to convert Graphene inputs into dictionary."""
dictionary = {}
for key in input:
# Convert GraphQL global id to database id
if key[-2:] == 'id' and input[key] != 'unknown':
input[key] = from_global_id(input[key])[1]
dictionary[key] = input[key]
return dictionary
this is the function
i am not really sure how graphene works so i am going with python knowledge mor ethan docs knowledge
afaik you should manipulate the dict key before doing user = ModelUsers(**data) to make sure you are giving the model the expected fields it needs
sorry about the typo
hmm
so
I have already changed the values
of the keys
def mutate(selfs, info, input):
data = utils.input_to_dictionary(input)
data['created'] = datetime.utcnow()
data['edited'] = datetime.utcnow()
user = ModelUsers(**data)
session.add(user)
session.commit()
return AddUser(user=user)
yes
otherwise i guess it will raise an error
yup
if the framework doesnt implements that for you and you really need this data, maybe you should implement those fields on the model
but the error it raises is invalid keyword argument for ModelUsers meaning that it consider Modelusers a dict??? no
hmm
That is the error
graphql.error.located_error.GraphQLLocatedError: 'created' is an invalid keyword argument for ModelUsers
i posted it earlier
i see, i guess this is relatred to the input field you are receiving
you can try add the fields to AddUserInput
hmm or not
you want to do this automatically i guess
ye
maybe you wil have to define these fields on the model
But there is nothing to change
I am just using
standard
formats
class ModelUsers(Base):
__tablename__ = 'users'
id = Column('id', Integer, primary_key=True, doc='User ID')
name = Column('name', String, doc='Name of the user')
username = Column('username', String, doc='Username of the user')
#hashed password TODO create hash function
password = Column('password', String, doc='Password of the user')
class ModelUsers(Base):
__tablename__ = 'users'
id = Column('id', Integer, primary_key=True, doc='User ID')
name = Column('name', String, doc='Name of the user')
username = Column('username', String, doc='Username of the user')
#hashed password TODO create hash function
password = Column('password', String, doc='Password of the user')
created = Column('created', Datetime ... )
edited = Column('edited', Datetime ... )
IDK how it works on Flask, but my shot is that you need to define something like this on the model
hm
let me add that
NameError: name 'Date' is not defined
i was so sure about that
try using DateTime
in this stackoverflow question, the answering guy just uses DatetTime
Maybe you could try
sec
ΛΛ
sqlalchemy.exc.ArgumentError: 'SchemaItem' object, such as a 'Column' or a 'Constraint' expected, got <class 'datetime.datetime'>
basically it is not the datetime module
I think it should be the mysql collumn type
ok, idk how is the expected behavior or data structure of SQL Alchemy, but, the datetime.datetime is a bulitin python function. Maybe you could try change the data['created'] = datetime.utcnow() for a datetime.datetime.now() idk
i will
ok
thanks a lot for help ^^^
at your service ΛΛ
π
Please can anyone recommend good resources or tutorials to LEARN WEB SCRAPING and DJANGO?
beautiful soup and requests have good documentation for web scraping
search for full stack python, they got good resource for it
hi people nice to meet you all. I am currrently trying to write a program using flask in pycharm
ive been looking at many tutorials however, none of them seem to help me
are there any experts in flask in here?
put down your question and people will answer if they can
applications = Application.query.filter_by((rate=0) or (rate=1))
guys this or doesn't work
how can i do for filter two types of applications? the applications with rate=0 and with rate=1?
is this a part of an if statement?
yes, more or less, there is an if that check if current_user is an admin
it doesn't work
"rate" is not defined, i think is because this is a query for a database so doesn't exist the == in the query language
if current_user.acc_rank >= 1:
page = request.args.get('page', 1, type=int)
applications = Application.query.filter_by(rate=0).paginate(page, app.config['APP_PER_PAGE'], False)
next_url = url_for('appstore', page=applications.next_num) \
if applications.has_next else None
prev_url = url_for('appstore', page=applications.prev_num) \
if applications.has_prev else None
users = []
for item in applications.items:
user = Account.query.filter_by(acc_id=item.owner_id).first()
users.append(user)
return render_template('storeapplications.html', title="Storico applications", app_user=zip(applications.items, users), applications=applications.items,
next_url=next_url, prev_url=prev_url)
else:
flash('Non sei un amministratore.')
return redirect(url_for('index'))
the rate is in the database
basically you are saying this:
if applications is equal to Application.query.filter_by((rate=0) or if the rate is equal to 1: do stuff
you are comparing not adding values
mm i have to filter both those with rate = 0 and with rate = 1, if i write (rate=0) it works but if i add another comparing it doesn't work
so you need AND
when you are making an if statement if you want to check equality you need to use == instead of =
mm ok i try
ok it works with ==
i've done this
applications = Application.query.filter((Application.rate==0)|(Application.rate==1))
You can't use python or statement with sqlalchemy
I mean you can but you can seriously fuck up sqlalchemy internals
mm it seems to work well for now
i'll change it if it will give problems
thank you for advices guys
ΞΏΞΏΞ·
ooh
u are using sqlalchemy?
rright i am so dumb, imagine i am using it right now
haha
π
Using graphene?
I am trying to create an api
what does a robots.txt mean when it says
Allow: /$
Disallow: /
so I can serve it as backend for my C# platform
the disallow is for the root, but what is the allow for?
@rustic pebble
Graphql api?
@spare canyon yep!
I can POST users to the mysql table correctly
but i havent found anyway to retrieve data from it
and form a request
in python
What do you mean
Basically I can insert rows into my tables but I cant retrieve the rows
I am not 100% sure how the graphql query system works
Can i see your schema?
sure
from graphene_sqlalchemy import SQLAlchemyObjectType
import graphene
import utils
from datetime import datetime
from database.model_users import ModelUsers
from database.base import session
class UserAttribute:
name = graphene.String(description="The name of the user")
username = graphene.String(description="The username of the user")
password = graphene.String(description="The password of the user")
class Users(SQLAlchemyObjectType):
class Meta:
model = ModelUsers
interfaces = (graphene.relay.Node,)
class AddUserInput(graphene.InputObjectType, UserAttribute):
pass
class AddUser(graphene.Mutation):
user = graphene.Field(lambda: Users, description='User created by this mutation')
class Arguments:
input = AddUserInput(required=True)
def mutate(selfs, info, input):
data = utils.input_to_dictionary(input)
user = ModelUsers(**data)
session.add(user)
session.commit()
return AddUser(user=user)
class UpdateUserInput(graphene.InputObjectType, UserAttribute):
id = graphene.ID(required=False, description='Global id of the user')
class UpdateUser(graphene.Mutation):
user = graphene.Field(lambda: Users, description='User mutated')
class Arguments:
input = UpdateUserInput(required=True)
def mutate(self, info, input):
data = utils.input_to_dictionary(input)
user = session.query(user).filter_by(id=data['id'])
user.update(data)
session.commit()
user = session.query(user).filter_by(id=data['id']).first()
return UpdateUserInput()
Where is your class query
different file
from graphene_sqlalchemy import SQLAlchemyConnectionField
import graphene
import users_schema
class Query(graphene.ObjectType):
node = graphene.relay.Node.Field()
#Users
users = graphene.relay.Node.Field(users_schema.Users)
userList = SQLAlchemyConnectionField(users_schema.Users)
class Mutation(graphene.ObjectType):
#User mutation
addUser = users_schema.AddUser.Field()
updateUser = users_schema.UpdateUser.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
Can you use query
Basically I can insert rows into my tables but I cant retrieve the rows
Can you elaborate on this
I can add users
to the database
Using the following query on postman
but i am not sure how to translate it to python
And I also want a way to read the database, or more like, scan through i
it
I am making a login/register page rn
So you want to query directly from database in python code?
What database and orm are you using
I want to do the following:
I am creating a python server using flask and I want to handle MySQL database requests with GraphQL. I am developing the UI on C#, .NET and I want a way to easily communicate between both
Basically I am stuck at sending/receiving info
I want to figure out what the request format should be
You don't know how to consume api from c#?
I am not sure how to form a proper request (:
Ah
So
Graphql reads from request parameters and body
If you are sending images, you send images in body as multipart form and query in the parameter with parameter name query
If you are just requesting data, in request body do
{"query":"query{ hello }"}
so in my case
this is my code:https://github.com/sneakykiwi/AIOapi
hm
i get this
anyone have experience with http requests, cookies and authentication and can offer some advice?
a little
i don't think i'm understanding the concepts
let me try to explain
i'm setting up a single session e.g. myHttp = requests.session()
and then doing a response = myHttp.get(url)
this is a login form and a cookie is set
i then post the credentials, login = myHttp.post(url, data=payload, cookies=response.cookies)
sounds reasonable
here is where it gets tricky, after the login it does a 302 redirect
sounds normal
in the redirect there is another cookie set
sure
this lands me to another page for MFA
i seem to be able to get through the login, enter my MFA but i think i'm stuffin the cookies up
I can't even imagine how that would work
in general, do i keep passing the cookies down the chain?
i noticed that i had to add allow_redirects=false to the login to allow me to at least pickup the auth cookie
In general, yes, I'd expect you'd always want to send back any cookies you've received
I sorta thought the session would do that for you
what MFA provider are you dealing with?
Azure AD
BTW, I've developed Backend APIs for C# programmers using FastAPI before, check it out if you only need restful API
Hello
why is backend restful API authenicating to Azure AD?
it's a cli tool that needs to auth, there is no API to my knowledge so its all login form magic
<nav class="navbar">
<div class="items">
<div class="left">
<i class="fas fa-users fa-lg" id="family_icon"></i><a id="family"> fami.ly</a>
<a href="#"><i class="fas fa-home"></i> Landing</a>
{% if not logged_on %}
</div>
<div class="right">
<a href="/register" id="right"><i class="fas fa-hand-point-up"></i> Register</a>
<a href="/login" id="right"><i class="fas fa-sign-in-alt"></i> Login</a>
{% endif %}
{% if logged_on %}
<a href="#" id="right"><i class="fas fa-paint-brush"></i> Customise</a>
<a href="#" id="right"><i class="fas fa-sign-out-alt"></i> Logout</a>
{% endif %}
</div>
</div>
</nav>
its for aws cli
it's basically this: https://github.com/asagage/aws-adfs-cli-mfa/blob/master/mfa-saml.py
ADFS is different then OAuth with Azure AD
in any case, the user should be authenicating and passing token to you
C# UI needs to handle this
under no circumstances should you post Azure AD Creds to your REST backend
as Azure SRE, if I found you doing that, I'd blow up every Azure AD application you made and kill all your sessions and likely invalid your MFA token
but I work in high security environment
makes sense, it authenticates the adfs, then passes over to aws to get a token
Nope
ADFS gets token
ADFS != Azure AD
Active Directory Federation Services is different then native Azure AD
This is how OAuth works with Azure AD, App -Send user to Azure AD-> Azure AD logins in the user -Sends Token back to application-> Application then presents the token to other applications -> they validate token with Azure AD
so when you make AWS calls, you need to already have a token and send that over to AWS
so in your example with C# UI with REST backend, C# app would login to Azure AD, get the token and then send that to REST API for it to validate or just pass the token every request
if ever get forbidden from AWS, you need to check token with Azure AD and either renew it or direct the user to log back in
and yes, it's a PITA
i think that makes more sense, thanks for walking me through it.
yeah, not having a good time right now. def a pita.
We don't interact with Azure when we get the token
we are just validating who the user is
we are B2B and Azure AD is by far biggest Identity provider we get asked to integrate with
which is hilarious since we don't use Azure AD
but that's OT rant
I have a bootstrap div that consists of 2 columns, and I have an image as the background for each column.
is it possible to have the image cover the entire left and right part (the remaining part of the page), instead of only the div it is in? "see image for details"
Quick question: I'm wanting to write a small, simple REST api for another application to use; hosting it on my server. I already have postgres installed and I want to just connect to it. Is Flask/Flask-restful a good solution for this?
If not, please recommend one
It is a good solution, although I hear fastapi might be better
With flask-jwt, how do you get it to return errors like it used to rather than just raising exceptions?
@steel tiger not sure but cant u just make a try/except?
No
It used to automatically return errors like "invalid authorization header" to the requestor
and what does itdo now?
hey
But now it just has an internal server error
cool
hmm
give me a sec to researc hthat
and hosting service on hostinger
i want to run cyber security , programming related QnA style forum
@steel tiger i found this
i will keep checking
do they will suspend my website for doing this?
Hm
Looks like it's an ongoing issue
@native tide why would they suspend your website?
are u using restapi?
@native tide how can we know how your website is down ?
How in the world would we know that
it can be for 50000 reasons
I want to create StackOverflow or math.stackexchange like website
i came here for discussion
But this channel is filled
well you need these:
frontend
either with cms
or u can coded
and backend server
MySQL, Python or PhP
Discourse is a good forum software
you can do whatever u want
??
Got it to work
what CMS should i use?
i want to create stackoverflow style website
@molten edge i like making my apps on .NET
If your going to try to make a clone of stackoverflow and you are on a python server; it would be fitting to use something like Django or Flask to build the website
uis*
(Both python web frameworks for building websites)
python server?
Go with flask
They can handle all the backend for you
Django has unnecessary shit
i know about php server, apache , niginx
Django for bigger projects not oneman projects
can i go with python web server?
Django is more suited to larger websites, flask is more suited to small websites and apis
Python web server?
@steel tiger care to explain how u fixed ur propblem?
Oh
This is a python discord server
So you get help with python-based projects here
do you know about Discourse or mybb or flarum software
or tell me what should i do to create stackoverflow style website
Not really a specific field for q&a sites
Learn either Flask or Django for all the internals of the website
stckoverflow like theme, and all the working of it.
Then learn how to setup NGINX for running the website and some Linux for deploying
So nginx is best for shared hosting
yes, i want to create forum website
Yes
with stackoverflow theme
Stackoverflow is just a blog site really
With a points feature that is a fancy like button
but they have cool theme, ranking roles, sliders, etc
You allow users to create posts and comments
Themes are different from all the deep-down workings of it
So after setting up nginx on my hosting service
I am hosting using hostinger
shared hosting
Nginx is the program that allows you to display content to visitors
Why hostinger and not something like DigitalOcean?
which is best nginx or apache or wamp/xampp
@steel tiger digital ocean only provide VPS
my website is a forum, online community.
and im begineer
Because databases and python running, blah blah
which is best nginx or apache or wamp/xampp
Basically
Use flask or django to make the deep down website stuff
Use nginx for "web server"
Use digitalocean/vultr/linode for server hosting stuff
And use plain CSS or some fancy Javascript for frontend (what user sees)
so application what are runnign on web server doesnot depend on them,
for example if i run nginx, in future sometings like this will happend that a certain app is not for nginx
If it doesn't work with nginx it won't work with anything
i already bought Hostinger hosting for 1 year
NGINX basically makes a html page forward nicely onto the internet
From private network -> internet
Can you cancel it?
A VPS is much more suited to this sort of task
i paid 48 usd for 1 year
Yes but can you cancel it
no
How long ago did you buy?

