#web-development
2 messages · Page 31 of 1
maybe pass apikey for those API that need it
Axios has no library for Python @vagrant adder ?
@gleaming herald use requests
I'd suggest aiohttp as well for async
He probably does not need it, he'll still be able to change later if required, stickng with requests to start sounds more sensible to me
Client side means from the browser @gleaming herald
may or maynot be the same
If you want from server(python), use requests
async is a concept
Client also means getting the requests or just consuming
Server side means serving the requests
that's what I thought @vagrant adder
@vagrant adder « client » side is simply « consuming »
Not necessarily in a browser
oh > okay
How to hide the download link in websites
like I have a user form where user puts in details
if they fill it then only the download should happen
but few of the people overcome this just by inspecting the download button and then getting the link directly
should I create a micro-service
just to get the form details verify the form and then give them downloadlink
It really depends on the details here - what is the download link, and what is the site with the form like?
@gleaming herald
donwload link is of PDF
site with a form is simple bootstrap/html/css site
@rigid laurel
In that case it depends on the level of security you need. You could probably just add a layer of obfuscation with JavaScript, but it will still be possible for them to get at the URL with enough effort
Okay ! Thanks 🙂
from flask import Flask, signals
from config import Config
from flask_sqlalchemy import SQLAlchemy, models_committed
from flask_migrate import Migrate
from flask_login import LoginManager
signals.signals_available
@models_committed.connect_via(app)
def signal_thing(sender):
print('hello first')
sender.print('hello this worked')
models_committed.connect(signal_thing)
I cannot get signal_thing() to fire when models are committed.
my database is updating with new fields as i see them in my webapp
I'm not sure if this is allowed, so please chastise me if necessary.
Anyone here good with email setup and avoiding emails being sent to spam?
One of the offtopic channels is probably a better bet than this one
Thanks
I have a django project base that I use for client projects. To start a client project, I make a new branch, and customize it on that branch. It then exists in that branch forever and is deployed from that branch. If a change is made in master that is wanted in a client branch, master is merged into the client branch. Is there a better best-practice for how I should be organizing this? It works, but I'm not completely happy with it
@lofty matrix why aren't you “completely happy with it” ?
I feel like there should be a way where you, for example, package the base project and package the customized apps or something
Do you have issues with your current workflow ?
I'm developing Rest api with Flask and Flask_RESTful but i have a strange problem. My project have 2 class named PermissionsManager and Permission. PermissionsManager contains special variables and this variables refer to Permission Class. And the strange things comes there.
Permission Class Structure:
name = "Permission-NoName"
permissions = []
def __init__(self, name, permissions, root):
*root stands for upper Permission Class
PermissionsManager Structure:
USER = Permission("USER", ["read:api_key", "use:api"])
SUPPORT = Permission("SUPPORT", ["ticket:edit", "ticket:close"], USER)
OWNER = Permission("OWNER", ["access:admin"])
The strange things is USER have all specified permissions but i want only have what i specified permission to USER. First of all i think maybe my "root" variable is wrong but thats not the problem because USER also have OWNER permissions. I can't figured out the solution, tried everything comes to my mind. I really need help. Thanks to everyone.
!codeblock @fast grove
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
Zamion, your problem is probably that when you access the permissions list, you're actually accessing the class variable "permissions", and not something local to the instance
This is often run into with lists or dictionaries, because they are changed in place. If it was a string, for example, you would have used = to assign to it, which would change the current instance instead of the class itself
best practice is to define those types of instance variables/attributes inside __init__, and if you still want a "starting permission set", name it base_permissions, perhaps
I thing ass well but while debugging print all class and method variable in init but prints clean list
Ohh i get it now
It may be the solution i will try in a moment
I will response to you
Here's an example:
!e ```python
class A:
permissions = []
def __init__(self, perms):
self.permissions.extend(perms)
print(id(A.permissions))
a = A([1,2,3])
print(id(a.permissions))
print(a.permissions)
b = A([2,3,4])
print(b.permissions)
@native root Your eval job has completed.
001 | 139815990494600
002 | 139815990494600
003 | [1, 2, 3]
004 | [1, 2, 3, 2, 3, 4]
That was really helpful i solved the problem and learned a important thing. Thank you for your help. @native root
👍
<script>
Lonestar.Inventory.ViewInventory.js.init(
document.getElementById('dnn_ctr787_ViewInventory_InventoryApplicationPanel'),
{
vehicles: ["1", "2"]
});
</script>
Could anyone help me write REGEX ?
What I want to capture from text above is this:
{
vehicles: ["1", "2"]
}
Hello can someone help me please
{% for post in posts %}
<div class="blog-post">
<a href="{% url 'post-detail' post.id%}" ><h2>{{ post.title }}</h2></a>
<p class="p"> {{post.content}} </p>
Posted
<span> {{ post.date_posted|date:"F d, Y" }}</span>
by {{ post.authoer }}
<hr>
</div>
{% endfor %}
Why do my posts are over eachothers i cant make my posts under eachother
<hr> is the line that suppose to separate between 2 posts
I think that's br
Also, 2nd line is finiky
Where were you
What do you mean where I was
I was texting you alot and u were ignoring
why does the 2nd line look fliniky ?
Ty saki for being a friend then gone
You literally said you don't want any friends
Also, this is web dev channel
I don't know what would url 'post-detail' mean
If i dont want any friends why did i tell you to be friends ?? Anyway let's continue in our discussion
post-detail is a html file that when clicking on the post
it goes there
to each post site
following its id
isn't url_for() function used for linking other websites
wait
are you doing django or flask
no, url_for redirects to another view
Django
ah
Hello. I am creating website using Django. I've got superuser called admin. When I login into /admin I"ve got this error message: You are authenticated as , but are not authorized to access this page. Would you like to login to a different account?
Can you help me?
@viral wasp what does this results in ? (to be run in python manage.py shell)
from django.contrib.auth import get_user_model
User = get_user_model()
admin = User.objects.get(username='admin')
assert admin.is_superuser
It works now. Thank you
Hello guys, I hope you doing well. I have a question about creating / updating a user instance from the django admin panel. I created a custom model where USERNAME_FIELD is set to email. But my django panel is showing me the actual username field instead of the email. How can I fix that ?
made this with help of a online beginner python tutorial using django now i want to properly learn web dev, so where should i start from ?
https://media.discordapp.net/attachments/618116184503615663/621741488606281728/unknown.png?width=400&height=196
do u guys know any good references or courses for django?
corey schafer one
I'm having some serious issues setting up npm + webpack on Windows
could anyone help me get through this painful experience?
pls don't tell me to do it on Linux because it's not for myself, it's for someone else
I assume you aren't using an ide?
All I remember is that Webstorm pretty much sorted out all the Webpack stuff for me
it was PowerShell's fault
never use echo to create a file on Windows, gdi
someone in the Reactiflux server figured out that the byte order mark was the problem
I have created a chatbot
does anyone have idea
how to expose a API out of this
like how do I implement this on a website
the backend is ready
it takes user input and responds accordingly
but they are not independent
if I say call me
it asks for a number
then responds
so the connection should be open
and the flow should not be broken
any ideas
In really unclear on what exactly you mean. But it sounds like you might need to do some research on sockets and websockets to see if they're what you need
Vs the other main option which would be a rest api
I have a question, is this the right place to ask?
I have a question about python flask app and how you share a connection pool across blueprints.
Using sqlalchemy and mysqlconnect
Being doing some research but would appreciate a pointer in the right direction
so i don't know specifically what happens with blueprints or a connection pool, but i've made use of closures in order to pull "outside stuff" into a flask app
def make_app(default_username='salt rock lamp'):
app = Flask.app(__name__)
@app.route('/user/create')
def create_user():
username = request.args.get('username', default=default_username)
return app
it might be a bad idea though
I would need to initialise the data pool once ... and access it on need
yeah so this would be app.py:
def make_app(default_username='salt rock lamp'):
app = Flask.app(__name__)
@app.route('/user/create')
def create_user():
username = request.args.get('username', default=default_username)
# ...
return app
app = make_app(default_username='Richie')
that said SQLAlchemy does its own connection pooling
I want to use sqlalchemy pooling
then i think just use the built-in sqlalchemy integration and it will do the pooling for you
What I don't understand is when u wish to use the pool set up initially in a blueprint
why do you need the database in the blueprint at all
I'm using ajax and jquery
ah
I also use ajax to get data to update the web page
ive never done this before myself but i thnk im converging on an understanding of how to do it...
are you using sqlalchemy ORM?
or just core
Want to use the ORM
so there are a few examples of usage here -- basically you can safely assume that there's an active session when writing your blueprint code
Created a web page which interacts with the server using ajax .. now wish to add the database ... but not sure how
# facebook/__init__.py
from flask import Flask
from facebook.views.profile import profile
app = Flask(__name__)
app.register_blueprint(profile, url_prefix='/<user_url_slug>')
# facebook/views/profile.py
from flask import Blueprint, render_template, g
from facebook.models import User
# The prefix is defined on registration in facebook/__init__.py.
profile = Blueprint('profile', __name__)
@profile.url_value_preprocessor
def get_profile_owner(endpoint, values):
query = User.query.filter_by(url_slug=values.pop('user_url_slug'))
g.profile_owner = query.first_or_404()
@profile.route('/')
def timeline():
return render_template('profile/timeline.html')
@profile.route('/photos')
def photos():
return render_template('profile/photos.html')
@profile.route('/about')
def about():
return render_template('profile/about.html')
(edited to use absolute imports for clarity)
so you just import your models and operate on them
if the flask app itself is set up right, you shouldnt have to explicitly make any db connections in the blueprint
Using ajax to update the web page ... these cant be in the blueprint?
not really
javascript has to update the page...
unless you re-load the page from the server, which isn't ajax
I wanted to create a dashboard like page ... so interaction updated different sections
so let's say you have https://myapp.example.net/index.html. you have some javascript that makes a request to https://myapp.example.net/user/123, and then more javascript updates the contents of index.html with the result of the request
we agree that's how ajax works, right?
Yes
What's your understanding of a blueprint?
once you register a blueprint, the .route-decorated functions are now part of the flask app's routing
that's pretty much it, along w/ some context you can define at the blueprint level
It sounds like it has to be static in terms of the data
not necessarily
it's just a collection of app routes
that's it
anything you can do with app.route you can do with my_blueprint.route
Can u pass a variable to a blueprint?
The data pool is defined in the same place as the blueprints are included. Was thinking perhaps it's possible to just pass it
Connection pool
i thought you were using sqlalchemy
which does its own connection pooling...
can you share some code
Perhaps my understanding is incorrect
can you write some hypothetical code that at least demonstrates what you want to do
Cant atm ... not at my computer
import flask
from myapp.models import User
profile = flask.Blueprint('profile', __name__)
@profile.route('/create', methods=['POST']):
def create_user():
data = flask.request.form
session.add(User(**data))
session.commit()
pretty sure you can just do that
Does anyone have a working example of sftp client via socks5? I am looking to webify this
wait @hot niche sorry i'm thinking django. those are django examples
anyway sqlalchemy should be similar... follow the guide in https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/
sqlalchemy does connection pooling
you dont need to explicitly set up or maintain one
it will establish a connection pool by default, automatically
you just use sqlalchemy orm and don't have to worry about the connection
In the pool you have for example 20 existing connections to the database.
Does it not create an object u have to request a connection from?
I'm just afraid it will create 20 new connections every time I try and connect to the database if I don't pass the object created
Eg
don't connect to the database inside the blueprint
import sqlalchemy.pool as pool
import psycopg2
def getconn():
c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
return c
mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)
Here you have a pool called mypool with 5 existing connections.
You use the object mypool to request an existing connection
because again, this is all handled in sqlalchemy by default
So how do I get the existing mypool object using sqlalchemy?
Above code creates the pool using sqlalchemy
... or is my understanding here wrong?
Session wont work as u need the pool available across all sessions
i'm not talking about a session as in a single HTTP connection or something
Cool :)
in order to get sqlalchemy and flask working together you need to create a scoped session
its a whole bunch of boilerplate
if you use flask-sqlalchemy everything is taken care of
adapted from https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/#a-minimal-application
import flask
import psycopg2
from flask_sqlalchemy import SQLAlchemy
def getconn():
return psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
app = flask.Flask(__name__)
db = SQLAlchemy(
app,
engine_options={ # kwargs passed to sqlalchemy.create_engine()
'creator': getconn,
'max_overflow': 10,
'pool_size': 5
}
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
user_blueprint = flask.Blueprint('user', __name__)
@user_blueprint.route('/', methods=['POST'])
def user_create():
data = flask.request.form
db = current_app.config['user.db']
db.session.add(User(**data))
db.session.commit()
app.register_blueprint(user_blueprint)
Hey everyone, sorry for the dumb question - I'm close to 0 experience with Flask, but decided to join the adventure as I have finally an application that can help my day to day job ( network admin ) which consist of an website to make API call to configure some of the devices, I have some guys of website running using Flask-admin, SQLAlchemy, however I have an issue with the DB- everytime I put an entry on the database and close the APP, the data is not saved and I'm struggeling identifying the fix for it
here is the snipset
app = Flask(__name__)
app.config['SECRET_KEY'] = 'changeme'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/database.db'
app.config['BASIC_AUTH_USERNAME'] = 'john'
app.config['BASIC_AUTH_PASSWORD'] = 'matrix'
#basic_auth = BasicAuth(app)
class MyHomeView(AdminIndexView):
@expose('/')
def index(self):
return self.render('admin/index.html', sites=Site.query.all())
db = SQLAlchemy(app)
admin = Admin(app, name='GTK Meraki Dashboard',index_view=MyHomeView(), template_mode='bootstrap3')
class Site(db.Model):
__tablename__ = 'sites'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
api_key = db.Column(db.String)
network_id = db.Column(db.String)
admin.add_view(ModelView(Site, db.session))
#admin.add_view(AdminIndexView)
Any help would be appreciate as I'm sure I'll have way more question
got this fix I guess, had a / too much and since Im on windows with this machine I put the absolute/path/to/the/database
@surreal thicket perfect :)
Thank u v much
Can someone help me in django? Im trying to just get a user input and store it, run it through a back end program and show the result on screen
I dont know what to do anymore lol
Ive been following along tutorials but none of them have anything that relate to getting a user input and then doing something to it and putting it back on screen
@trail glacier there are a few layers to this: backend data processing, transporting data from the frontend to the backend, and the frontend itself for both receiving and displaying data.
starting with the backend, you would use normal python code. if you need to interact with the database, use the django orm. otherwise you just write regular python functions that do the required processing
for the "middle" transport layer, usually you would send an HTTP request to a special URL. conventionally you would send a POST requesst with data contained in the request body (e.g. in JSON format), or a GET request with data in URL parameters (the "?a=1&b=2" stuff you see on the end of a URL). maybe your webpage is /index.html. let's say you are accepting text input from users and fetching stock prices. so you might have the user send an HTTP GET request to /stocks?symbol=GOOG&start=01-01-2015&end=01-01-2017&frequency=daily, or an HTTP POST request to /stocks with request body {"symbol": "GOOG", "start": "01-01-2015", "end": "01-01-2017", "frequency": "daily"}
for the frontend, it depends on the desired interface. the simplest thing you can do is make a webpage with an HTML <form> in it. the user submits the form, and that makes a request to the backend. django has special support for forms, which might be a good place to get started https://docs.djangoproject.com/en/2.2/topics/forms/
@surreal thicket Im basically transporting a string and getting back like a list
but im not working on that part
I just need to send a string to the backend and then display the list it returns on the webpage
so you want to update the webpage without reloading it?
Would that make a difference?
it's a bit more complicated, because then you need some javascript in the webpage to modify its contents without refreshing
i guess you could serve the content in an iframe or something, but that's also complicated (and probably uglier visually)
ok. and how do you want the user to enter this data?
What ways are there? I was just thinking like a form on the webpage.
and thats what I've been trying to do for the last like day
a form is probably easiest, yes
so you'll need:
- a URL for the input page
- a URL for the page with results
- a view for the input page, containing a form that makes a request to the 2nd URL
- a view for the output page, which puts the processed output into HTML
does that make sense?
wdym a view for x page
nope!
Are these "views"
def home(request):
return render(request, "home.html")
def about(request):
return HttpResponse("about")
in views.py
xd
yes
django is a big piece of software, it's not a good one to learn from scattered tutorials...
Yea, uh.
you might want to work through the very, very comprehensive django tutorial on the website
at least parts 1-4
have you gotten to part 4 yet? it basically explains how to do what you're trying to do
Templates?
actually read the text, don't just skip to the examples. it pretty clearly explains how this all works
and yes it covers your use case
Cool I'll read through that. I'll @ you here if I have any more questions if thats fine xd
just post here, someone will answer
kk
@surreal thicket sorry for @'ting you but Im going to have two models right? one for the input and one for the output?
you dont need any models at all unless youre storing things in the database
Oh what
So I can take the input straight from the view to the program that gives the output?
what program gives the output?
the view receives the request from the form, runs the program, and then return the output with render_template
a python script
What's the best way to paginate a long form? A few thoughts came to mind, mainly doing div hiding, and using Javascript to dynamically expand divs/close them, but I want each div to appear on the same part of the page, i.e. near the top. Another thought was to use multiple forms, and return each successive form from the view in flask but that seems extraordinarily heavy handed, so was wondering how people have handled this
due to the API this form sits in front of, removing inputs isn't an option without sacrificing a lot of control either
hey guys, still working on my Flask/API project, one think Im working on is a way for the user to upload a CSV file that contain some information of devices where the API will perform the action (ie: renaming the devices) - since the CSV can have up to XXX devices, each devices will perform a call to the API and rename, the API will return a 200 SUCCESS code, any tips on where to start for the user to be able to see if all the devices return a 200 OK or a 404? shall I log the call to a Database entry and have it then return as status on the website?
@dense ember the status code should refer just to the CSV upload process imo
then you can return the success or error status from each device in json or something like that
oh I see, creation of a json that contain all the call - no idea how to do that but I see the logic behind
you can return a CSV too
input:
a8ja2,https://api.example.net/1
0jjw0,https://api.example.net/2
output:
a8ja2,200,OK
0jjw0,401,"Unauthorized, please log in"
something like that maybe
I see - I will google more on that thanks @surreal thicket - flask is new to me apologize for the question
this isn't really flask related
it's up to you to determine the output format
so do whatever is easy for you and your users
the output is return to me from the API I used, so it return the data on the browser at the moment for a single call, the difficulty I have here is that doing it on CSV while you have 100+ devices is how to handle each devices to ensure it's 200 SUCCESS
cn you clarify what you're trying to do exactly
user upload a CSV file that contain some information,
the website will then make an API call (PUT) using the serial number from the CSV ( devices/{{serial}} ) and push a new device name for each devices ( up to 1000 devices on the CSV )
I somehow need to return the success code so the user can confirm if it perform OK
example of what I have working so far for a single type of request
def fix_firewall(site_id):
site = Site.query.get(site_id)
apikey = site.api_key
networkid = site.network_id
payload = "{\n \"rules\":[{\n \"comment\":\"Inter Vlan\",\n \"policy\":\"deny\",\n \"protocol\":\"any\",\n \"destPort\":\"any\",\n \"destCidr\":\"192.168.0.0/16\",\n \"srcPort\":\"any\",\n \"srcCidr\":\"192.168.0.0/16\"\n \n}],\n \"allowLanAccess\":true\n}"
headers = {
'x-cisco-meraki-api-key': (apikey),
'Content-Type': 'application/json'
}
resp= requests.put("https://api.meraki.com/api/v0/networks/%s/l3FirewallRules" % (site.network_id), headers=headers, data=payload)
return str(resp.json())
this code allow me to return the respond from the API call, since the CSV will have more than 1 call, that why I struggle, I'm also a beginer coding so dont mind if the code is not clean
the serial is to make the call on the API, name is the setting we're pushing, address and note are optional - if I have the name I can replicate arround it
yeah, why not send a csv back? like
serial,status_code,status_reason
Q2MD-SDVU-XP9X,200,OK
that would also work indeed yes
you have 3 "layers" to this application:
- flask - receiving and responding to user input over http
- csv handling - extracting input from the user's csv, and formatting output back into csv
- processing - doing whatever it is you need to do
i recommend putting each part in a separate module, so you can develop and test each layer independently from the othres
my-project/
requirements.txt
http_server.py
csv_handling.py
processing.py
tests/
test_http_server.py
test_csv.py
test_processing.py
there are more sophisticated file layouts possible of course, but that's absolute minimal
that said i recommend a "setup.py" based setup
my-project/
setup.py
requirements-dev.txt
src/
myapp/
__init__.py
http_server.py
csv_handling.py
processing.py
tests/
test_http_server.py
test_csv.py
test_processing.py
that seem really good setup, right now on my existing code everything is in app.py making it hard for testing - I'll have to start from scratch at one point ( again my flask/python skills is beginer )
if __name__ == '__main__'
This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the __name__ special variable is automatically set to the string '__main__'. Conversely, when you import that same module into a different one, and run that, __name__ is instead set to the filename of your module minus the .py extension.
Example
# foo.py
print('spam')
if __name__ == '__main__':
print('eggs')
If you run the above module foo.py directly, both 'spam'and 'eggs' will be printed. Now consider this next example:
# bar.py
import foo
If you run this module named bar.py, it will execute the code in foo.py. First it will print 'spam', and then the if statement will fail, because __name__ will now be the string 'foo'.
Why would I do this?
• Your module is a library, but also has a special case where it can be run directly
• Your module is a library and you want to safeguard it against people running it directly (like what pip does)
• Your module is the main program, but has unit tests and the testing framework works by importing your module, and you want to avoid having your main code run during the test
I see - I will have to rework my structure and potentially start from scratch, what I have right now work for my usage ( minus the CSV feature ) but it seems more robus with the structure proposed
you can probably gradually modify it over time
doubt you have to start from scratch
but yes, it takes some time to learn good development practices, but they make life a lot easier when you do learn them
not sure, I feel my structure is messy and I agree - I really want to dive into the coding side now, python is nice for a network admin ( that what I do as work ) and flask seems nice side as well
not great but that what I have right now, everytime I refresh and it work I feel joy inside 🙂
I don't know what I'm doing wrong.
How do I put in the syntax?
I didn't quite know where else to put it so I put it here.
I'm trying to display a video but it won't work.
<iframe src="[video file path"></iframe>
Ok.
iframes are still a thing?
It didn't work.
@native tide I'm confused. How are you learning web development and are you using https://caniuse.com/ ?
I am trying to follow tutorial but it's kind of hard because I don't know how the embed the video.
I don't know if I need to replace this basis for under-dashes or not.
What are they suggesting you do?
Also what is the tutorial?
Lesson Code: http://www.developphp.com/video/JavaScript/Video-Player-Custom-Controls-Programming-Tutorial In this first part of the tutorial series we will d...
I have to put in a type of video.
Look into https://caniuse.com/#feat=videotracks
Ok.
Errr... wait, wrong thing
There
Is it supposed to have the code or something?
Check the resources if you need code
It's better to read the specification to understand what it's doing rather than copy/pasting code though.
I'm about to work on the frontend for website, it's a college project... and I have my setup ready to work with webpack, but I don't know what approach should I take to write JS and CSS
I'm not going to use any libraries for one-page sites, like React or Angular
is there any recommended way to organize the code? should I bundle everything in a single JS file?
It depends how much js you will end up with
yo I got a question, i hear about flask all the time but it was kind of annoying figuring out how to handle async requests and functions with it so I ditched it and went with Sanic. is Sanic much better than Flask though? I hear about Flask more than I ever hear about Sanic framework
They are different. There is also Tornado you may want to look at. Each have their own set of libraries to go with.
Generally it's easier to get along with non-async frameworks due to them being older and more mature. So async-based implementations are much less widespread as they serve a very specific purpose that does not give much benefit in general use case.
But does add quite a bit of complexity.
So no, it's not better. It just serves a different purpose and may be better for a particular use case and problems that asyncrhoniousness is designed to solve.
But in what modern age of applications would you not have a web server doing asynchronous stuff though
cuz like most of the time ur getting data from a db, which needs to be done asynchronously so would flask not be an option for that
DB access doesn't have to be asyncrhonious, unless you have got a huge latency and your webserver is in Japan while db server is somewhere in NA with terrible connectivity.
Quite often webserver and db server are in the same datacenter, or even on the same server, so the performance gain you'll get from going async will hardly be noticeable for average user.
It all very much depends on your particular use case and problems you are trying to solve. For a generic database-backed website as they are right now I would not go for async implementation.
Yeah. Flask is more than adequate til your application gets to huge sizes
Even for huge sizes - there are still docker+swarm (or kubernetes/ecs, whatever you prefer) that are much better for scaling then async will ever be.
Depends on the API in question.
Quite often - no, they are not. Most of the Django (and thus DRF-based) websites are backed by gunicorn with a few workers. Neither Django nor gunciorn are async afaik.
APIs are multithreaded/multiprocessed or loadbalanced towards multiple containers most of the time.
Hello. I want to make register page with SweetAlert2. If user enters username that already exists in database alert has to show up. What I'm doing wrong? https://pastebin.com/xwDKmtce
hi, I have a simple flask server and frequently see requests like these in the logs: xxx.xx.xxx.xx - - [13/Sep/2019 04:16:54] "CONNECT www.baidu.com:443 HTTP/1.1" 404 - xxx.xx.xx.x - - [13/Sep/2019 04:16:56] "CONNECT www.voanews.com:443 HTTP/1.1" 404 - xxx.xxx.xx.xxx - - [13/Sep/2019 04:16:56] "CONNECT cn.bing.com:443 HTTP/1.1" 404 - xx.xx.xxx.xxx - - [13/Sep/2019 04:16:57] "GET http://boxun.com/ HTTP/1.1" 200 - xxx.xx.xxx.xx - - [13/Sep/2019 04:16:58] "GET http://www.rfa.org/english/ HTTP/1.1" 404 - xx.x.xx.xxx - - [13/Sep/2019 04:16:58] "GET http://www.epochtimes.com/ HTTP/1.1" 200 - xx.xxx.xxx.xx - - [13/Sep/2019 04:16:58] "GET http://www.123cha.com/ HTTP/1.1" 200 - xxx.xxx.xxx.xxx - - [13/Sep/2019 04:17:00] "GET http://www.wujieliulan.com/ HTTP/1.1" 200 - xxx.xxx.xxx.xxx - - [13/Sep/2019 04:17:00] "GET http://www.ip.cn/ HTTP/1.1" 200 - x.xxx.xxx.xx - - [13/Sep/2019 04:17:03] "GET http://www.minghui.org/ HTTP/1.1" 200 - (IPs redacted)
why are they accessing other sites over my flask application and how can I stop it from happening?
is your app proxifying these requests?
maybe, idk
it's just a simple flask application, I don't intend on it proxying anything
you answer 404 to most of them, so i would say no, not sure why you answer 200 to some though
is this in the logs of your app or of your webserver?
when i do curl --connect-to google.com:80:tshirtman.dev:80 http://google.com/ i get a 200, because my nginx returns the default virtualhost, and i didn't put a python app behind that, but i guess if i had, my app would get the same kind of request as you see, and it would try to answer with the asked route, disregarding the host
(of course http only, if i use https i get a certificate error for obvious reasons)
ah yeah, so it directly gets it
so can I prevent this from happening?
well, first you probably shouldn't have your flask dev server exposed like this, at minimum you should put a reverse proxy in front of it, nginx is a good choice, apache as well, or lighttpd, there are certainly a lot of other ones, but these are well known and serious options. Then you could configure them to have a virtualhost for your website domain and to route the requests to it to your flask process (which should be served by something like gunicorn or uwsgi or something else instead of the flask dev server), so only the expected requests ever reach your python code.
well, sadly it's still a door on the internet, and people (or well, bots) are going to randomly knock on it
right... I was wondering if there's a way to prevent flask from opening the door for those proxy requests (?)
having the flask dev server exposed mean you can easily give control of your server to a crafty person
how come
debug mode, this gives a console when they hit an exception, which might be easy to trigger if they send weird requests
I have disabled debug mode
that's the most obvious one, but even if you disable it, it's not recommended for production, so the people writting it didn't have security as a concern when they wrote it, so there might certainly be more
okay... so just using gunicorn would prevent those type of requests?
or do I also need nginx or apache
no, it'll just be a more production ready to convey them to your app
i never used gunicorn without nginx or apache, not sure how that would work
yw!
does anyone here know how to make a post request with sanic
with data and headers
async def exchange_code(code):
config = load_config()
config['code'] = code
headers = {
'Content-Type' : 'application/x-www-form-urlencoded'
}
resp = await app.post(uri=TOKEN_URL, data=config, headers=headers)
print(resp)```
looking @ the documentation and they dont even mention anything about those 2
that's not what .post does...
Add an API URL under the POST HTTP method
app.post(url) is a shortcut for app.route(url, methods=('POST',))
sanic doesn't make requests. it handles them. use an aiohttp ClientSession to make outgoing requests
ok
as in templates?
it can serve static files but it doesn't have rendering built-in
you have options: https://github.com/mekicha/awesome-sanic#frontend
I didn't get any traction in #414737889352744971 over the last couple hours, so i'll ask again here in case someone had that channel muted.
anyone here used fabric to automate server deployment?
]I'm working through obeying the testing goat, and i'm on the chapter on automating deployment to a production server.
I've set up an ssh pair at ~/.ssh/id_dsa{,.pub} which is NOT password protected, and I can ssh in with just ssh Kylan@superlists-staging.aviananlyst.tk My username on the server and my local computer is the same, as is the sudo password. When I try to run the fab script, i get whats in the picture. It doesn't take my password either it just keeps prompting me for it. Any ideas?
passing the ssh key location explicitly results in the same issue
https://cdn.discordapp.com/attachments/414737889352744971/622980030070390785/unknown.png
https://cdn.discordapp.com/attachments/414737889352744971/622980810122723338/unknown.png
@mint shuttle that's a message comfing from SSH, somehow the config isn't right
I didn't have a config file before. I just looked it up and tried to make one with similar results. here:
(i did check that with the config file i can now just do ssh superlists-staging and it connects succesfully
with no pw prompt)
hi guys, i'm having an issue with django datetime field
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
print(request.POST)
data = request.POST
dt = datetime.strptime(data['date_posted'], '%d-%m-%Y %H:%M:%S')
form.instance.date_posted = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
form.instance.author = self.request.user
print(form.instance.date_posted)
return super().form_valid(form)
ValueError: The News could not be created because the data didn't validate.
the form goes into error because datetime format isn't correct
but when i try to do the same from the django manage.py shell
it works
so i was wondering how can i correct this issue
this is from shell
>>> from news.models import News
>>> from django.contrib.auth.models import User
>>> admin = User.objects.get(username='admin')
>>> n = News(
title="test",
content="testing",
link="https://testing.com",
data_posted = "2019-09-13 15:35:34.234588+00:00",
author = admin )
this works
!e ```python
from datetime import datetime
dt = datetime.strptime("10-12-2019 10:10:10", '%d-%m-%Y %H:%M:%S')
print(dt)
print(dt.strftime('%Y-%m-%dT%H:%M:%SZ'))
@native root Your eval job has completed with return code 0.
001 | 2019-12-10 10:10:10
002 | 2019-12-10T10:10:10Z
is the reference for supported datetime input formats
your strftime format is not one of them
thanks @native root
but there form.instance.date_posted = dt.strftime('%Y-%m-%dT%H:%M:%SZ') i'm correcting the format
You're turning the format into 2019-12-10T10:10:10Z, which isn't on the list as far as I can tell?
You can always just try it in the shell as that
but the way that i'm doing it should work right if i replace the format ?
I would assume so
hello friends i am usinf open weather api and i am getting this error in django
KeyError at /
'main'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.2.2
Exception Type: KeyError
Exception Value:
'main'
Exception Location: C:\Users\Deepak\Desktop\weather\weather_places\views.py in index, line 27
Python Executable: C:\Users\Deepak\Envs\weather_app\Scripts\python.exe
Python Version: 3.7.3
Python Path:
['C:\\Users\\Deepak\\Desktop\\weather',
'C:\\Users\\Deepak\\Envs\\weather_app\\Scripts\\python37.zip',
'C:\\Users\\Deepak\\Envs\\weather_app\\DLLs',
'C:\\Users\\Deepak\\Envs\\weather_app\\lib',
'C:\\Users\\Deepak\\Envs\\weather_app\\Scripts',
'c:\\users\\deepak\\appdata\\local\\programs\\python\\python37\\Lib',
'c:\\users\\deepak\\appdata\\local\\programs\\python\\python37\\DLLs',
'C:\\Users\\Deepak\\Envs\\weather_app',
'C:\\Users\\Deepak\\Envs\\weather_app\\lib\\site-packages']
Server time: Mon, 16 Sep 2019 15:01:49 +0000```
That sounds a lot like its against the sites TOS which means this server can't help you
Hey guys. I'm following along with a Corey Schafer Django tutorial, and while the code with the error message does run and work fine, I'm wondering if I'm doing anything wrong. Pycharm has never made mistakes like this before, which is why I ask. I've been encountering a lot of problems with importing modules in different directories with Django. I prefer to use absolute imports (django_blog.users import views as user_views), but when I run this Django returns ModuleNotFoundError: No module named 'django_blog.users'. I feel like I'm losing it lol, any help would be appreciated.
INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig' ]
users yes, and django_blog is just the project name, and the folder name for settings.py and the others (urls.py, wsgi.py, init.py)
I've done projects before with absolute imports, there just must be something wrong somewhere and I have no idea
The image shows you using an implicit relative import, not an absolute import
Implicit relative imports won't always with out of the box in py3 so if you want a relative import it should be explicit (using the dot at the front)
Did an absolute import also not work?
Maybe it's a different story for django
For an absolute import to work, the package must be in sys.path
And with simple apps this can be accomplished by relying on the python -m command when you run your script
Because it will add the current working directory to sys.path with -m
Don't know how django works in that regard
Can anyone help me with some concepts on APIs
Is it possible to keep a connection open
and receive input according to the need of API
like call the client with a message and then client responds with another message and the flow continues in the API from that point
any ideas ?
@proper hinge Correct, an absolute import doesn't work (from django_blog.users import views as user_views). While this logically seems fine and PyCharm autocompletes/is happy with it, running the server gives me ModuleNotFoundError: No module named 'django_blog.users'. It isn't an exception that crashes it, but rather an error that prints out from the server running
ok, I found out the problem after consulting with the django discord server. Pycharm considers the root folder your cwd, when in reality it is the django root folder. So all I had to do was mark the Django root directory as "Sources Root" in pycharm, and everything magically worked. Thanks for your time anyway Mark.
@gleaming herald with HTTP REST APIs at least, I think it is always sessionless, meaning authentication information is sent along with the data every time
Damn !
So you cannot keep the connection open
And send some request and response
With an API
How bad is that
Actually I'm supposed to load this large file when connection establishes and perform some operations with multiple requests from client
Now I have to load every time thw file the client request something from data
How inefficient is this :/
if I understand you correctly, ideally you can just send back the piece(s) that have changed from the larger file
It's not about sending back
It's about not loading a huge file in the start
Even though I send back a small part
Next time a request comes I need to load the damn file again 🤦♂️
@native tide
Are there any Flask developers here who are familiar with dynaconf..?
Hey guys, anyone know how to 'hide partially' some field in Flask-Admin? I just want to display partial character on a specifc field on the DB
Define partially
from fastapi import FastAPI
from starlette.responses import HTMLResponse
from starlette.websockets import WebSocket
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@app.get("/")
async def get():
return HTMLResponse(html)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
@proper hinge I found it
@vagrant adder I have an API key which are display in full, I want to add few character of that like: *************abcd for example
Really blocked on my project with figuring out how to configure dynaconf, if someone can help I'd be ecstatic!
@dense ember
You can query that key and encrypt/encode and send that to frontend
Damn, Dynaconf must not be very popular 😛
Guys is django alone enough to make a good website?
Like can I start making a site with 0 experience at other languages
a lot of good websites are done with django, but you are not going to learn django in a day, but you can learn with it and build good websites, django is big, there is a lot to learn.
Ye i know but I mean if I just learn django for now will it be enough
also, when you have a website working on your machine, don't expect that you can just put it online and receive thousands of visitors, it'll likely be very unoptimized at first, as django makes a lot of things easier for you, without telling you about the cost, so the shortcuts it gives you can make the website very slow. Of course it's possible to do fast websites with django, but your first website will certainly not be.
Oh ok ty
got something funny happening in a django 1.11 project; when i try to run the test suite, sometimes everything is great, and other times (same settings, same everything) i get this error: cPickle.PicklingError: Can't pickle <class 'unittest.loader.ModuleImportFailure'>: attribute lookup unittest.loader.ModuleImportFailure failed
I am trying to make something similar to this http://exampledjango.getstream.io/ but with a rating (0-5) instead of Pin option. I am having trouble interacting with each Photo's model.rating I can't interface with object from the DB in the form. I can't figure out how to get an instance of the Photo Model when the form loads which would display proper rating. Still working on getting POST to work properly too.
I came across this Django documentation page which seems to be so close to what I need
https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/
>>> form = ArticleForm(instance=article)```
But i need `article` to not be 1 specific item but for each object displayed on page.
I just haven't found anything specific to a DB heavy/Instagram like web page in my past searchings.
I am following along with Corey Schafer's Django framework site.
My project is here: https://github.com/Benerman/viewfinder_project/tree/master/viewfinder
Based on what you've described I don't think Django's form handling is a great fit for that - personally I'd rather set up an endpoint to post ratings to from javascript.
I have discovered my pickling error is due to trying to run tests in parallel; if you get an ImportError while testing with --parallel it fails with a cryptic pickle error. This is fixed in python 3.5 i believe? of course, I'm working on the tests for this app because we have lots of upgrading to do 🙃
hey guys im rendering out a bunch of form data like this
im using mode field sets
is it possible to have a delete button beside each one of them? or below
under each form
nvm i implemented it in a different way
nope
Thanks @magic blade I will look into JS solution for this. I already display the rating with CSS but can't update the rating.
This might be a silly question, I've done almost nothing with front end stuff, but is there any common approach or software package for creating charts and such (pie chart, bar graph, etc.) in a web page? The visualization specifically. I'm considering building a small company-internal site for representing some business metrics visually.
Chart.js
Which is better for web dev: JavaScript,HTML and CSS or Python,HTML and CSS
Python, Javascript, HTML, and CSS
😐
what are you going to use Python for?
by Python i actually meant Flask or Django
Looks great, thanks @vagrant adder
is there a different flake8 setup for django?
but is Flask good for building a website too?
Flask and Django are both good for building a website. It depends on the person and what they want to do. Most people say Flask is easier to learn and more rapid in application development, whereas Django scales a lot better. I like to think long term, so scaling is important to me. It is a bigger learning curve, but I have never been afraid of a challenge
Hi guys, are there any resources that you guys recommend for learning Django? or just go through Django docs?
Django Docs. Then get a few courses off of Udemy or follow detailed ones on Youtube if you can't pay for them
@native tide I've made a good sized flask app, and am now doing a starter django project currently. Flask doesn't require much knowledge at all to start building basic dynamic websites. Django contains a lot of functionality inside of it, far more than Flask, so there is quite a bit more to fully "get" it. The big advantage though is there are things Django can do in a few lines of Python and HTML that would require 30 lines of Python for Flask, as well as 30-50 more HTML lines. So I'm starting to see how massively powerful it is once you start learning these things.
One nice thing though is that Jinja and Django Templating Language are nearly similar
Wow , ok thx for the advice guys
I made a CHOICE FILTER in Django in order to filter my posts.
Howeve i can't both Filter and Search for the posts.
Becaude if Meta fields is a list, you can choice but if it ia a dict you can type and search
This is my filter.py, is there a way to use both fields?
Sorry if the question is not clear enough, i couldn't find anything on the internet
I was following this tutorial:
https://youtu.be/nle3u6Ww6Xk
In this tutorial you will learn how to implement a filtering system with django using the django-filter package. 7 Tips For Getting Better At Django: https:/...
how can I stream updates while my flask app is processing stuff?
with yield
iirc, something like ```py
@route('/something')
def something():
for i in range(1000):
yield str(i)
will work (i didn't do any flask in a long time, so the details may be wrong)
google's failing me. where do you conventionally store data that populates templates in a flask project? columns.yaml, in this case
│ app.py
│ columns.yaml
│
├───static
│ styles.css
│
└───templates
index.html
hey @viral sinew do you encounter the problem where the CSS styling isn't being applied to your web app
Flask web app
like when i specify the styling like so <head><link ref='stylesheet' href='{{ url_for('static', filename='css/main.css')}}'></head>
what is the cause?
its pretty annoying actually
anyone here has experience with customizing python-social-auth flow?
currently i have a stateless API Django app (using JWT for auth) and trying to add login with google/fb stuff
the default flow is highly bound to django default auth with session
btw i'm not using drf as well
I am hella mad with Flask, lol.
Can someone tell me the difference between using Jinja2 and using Vue.js build? Because I was mixing Vue.Js app with a Flask API backend, but I dont really understand at all, because I've seen that we are using templates in both ways, and also using jsx syntax with them...
And also its a different way of passing data when we are using a flask API, when I used jinja was more like passing data from the DB directly to the template (does that method have a certain name?), can I do that with Vue? It seems like I can't. I think with Vue I need to use Axios to request the data from an API... Its more like a confusion, I hope I got to understand.
@sinful pulsar I used google oauth API and also the Google Sign In API [https://developers.google.com/identity/sign-in/web/sign-in], they have snippets did you check them?, and also in Facebook Developers they have documentation about that, you need to create a dev Account and ask for a secret credential as api-key.
hello
Not to be rude but. I noticed that when i ask a question, it just gets ignored
and i noticed its not just me
I've had the same happen. Often it's be because no one knows the answer
Now often it's that some other more answerable question gets in the way
You just have to accept it
@native tide shouldn't it be
<!DOCTYPE html>
...
...
<head>
...
<link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">
...
...
</head>```
Also be careful mindful using single and double quotes. You only used singles when you should have used both
@native tide That's daily basis, bro, that's why I almost all the time do my own research...
And I also understand that I don't own others time.
@limber kayak it's... generally wisest to not mix the vue and python code. serve the API via flask/python, consume it via vue/js. if you must generate js from jinja templates (please don't) then you should probably change the template escape syntax (you can easily change vue from, say, {% to $$[ or some such thing) or just completely escape huge sections of your js from jinja
but there is almost no scenario where any of this is necessary or a good idea
with vue you can and should use axios as an http client. vue used to have one built in but they no longer do, many folks bind axios to Vue.$http which was how you accessed it when it had its own client
serve your data from flask via REST, all is well, they can talk to each other but do not depend on each other and can live in different places
google/fb auth is always a bit tricky. oauth in general is annoying to deal with yourself. you can do it entirely in js, but if you need to do stuff with the user's fb/google account from your server you add a step after the js login where you get the id token for server-side use and then store it somewhere (probably by sending it to some flask endpoint)
auth in general is extremely annoying and usually a great thing to offload to a third party to deal with (like firebase or auth0)
Dude took of his time to help, that's a lot to me, @junior cloak . Thank's.
this is my layout.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css')}}">
{% block br %}{% endblock br %}
</head>
<body>
{% block con %}{% endblock con %}
</body>
</html>```
i made a home page :
{% block con%}
<div class="topBar">
<h1>The home page</h1>
</div>
<div class="container">
<p>This is an web app</p>
<p>Should be written in choco font</p>
<p>color text</p>
<h4>Even This H4 tag</h4>
</div>
<div>
<form class="Buttons" action="{{url_for('about')}}">
<button>About</button>
</form>
</div>
{% endblock con%}```
but i noticed i can't add styling to the Button to thee about page
please help
this is the css
font-family: sans-serif;
background-color: honeydew;
}
.topBar{
background-color: darkgreen;
margin: 0;
text-align: center;
}
.container{
color: black;
margin: 0;
background-color: forestgreen;
text-align: center;
font-family: cursive, sans-serif;
}
.Buttons{
color: darkgoldenrod;
border-width: 2px;
border-color: black;
font-style: oblique;
}
You're using ".Buttons", but the button that you're talking about has no class assigned to it.
So fix it, change the button code for this: <button class="Buttons">About</button>
And that's all. You added the class to the button, that's the reason why the css is not being applied to the button, because you didnt assigned the class to the button.
So its like "Man, you are going to paint the houses that I tell you with color green?" But I am waiting for you to specify the houses that I am going to paint, but you don't say nothing so I don't paint no one, but I keep the green color and my tools. That's what you did.
@native tide
If I use flask_bootstrap, shouldn't flask itself create boostrap links in the <head>?
@little shuttle a single ChatInstance can be associated with multiple Users?
also you've got some kind of circular dependency between ChatInstance and Message
or are those the auto-created django ones
(as opposed to actual foreign keys in your database)
excluding reverse-links, maybe you could have something like this, although i feel a weird about having users linked in 2 places (chatinstance & message)
User
- name
- time_created
Message
- sender -> User
- chat_instance -> ChatInstance
- time_sent
- content
ChatInstance
- users -> User (many)
- time_created
Hello!
I have a doubt .. try to reach 10/10 using pylint is really necessary?
in my flask application I'm using factory method and in my model.py pylint says:
Instance of 'SQLAlchemy' has no 'String' member (no-member) all the methods I founded just ignore the problem.. but nothing to resolve this..
SQLAlchemy is a good option for ORM or has something better?
Hello All
I have a question, that I was hoping you could help with
I have a shared hosting on GoDaddy
I would like to run a python script from php.
Search, I a way to do so using Shell_exec
However, I have not had success and found out that shell_exec was disabled and cannot be enabled on Godaddy's shared hosting
My question is, what way would you recommend me calling a python script from a shared hosting linux server?
Should I attempt to use Javascript instead?
Need help with a JS function to save a randomly generated background color so far I have this
`<button onclick="colorchange()">test</button>
function colorchange()
{
var a = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var c = Math.floor(Math.random() * 256);
var color = "rgb(" + a + "," + b + "," + c + ")";
document.body.style.background = color;
}`
Should I use local storage or sessionstorage and how to use it here
P.s : sorry for interupt
Well session storage only saves it for the duration of the current session
where as local storage persists
I don't think local storage is cleared unless done so explicitly by the user 🤔
What do you plan to do with the colour once you save it anyway?
I just want it for the college projec
I know u can save color and retrieve it after refresh page but I wonder if I can retrieve after saving and restarting the browser
Yeah, sounds like you need localstorage
Have you attempted to use it yet?
MDN should has some examples
Not really I am very new to JS I only know html for now
It's for a website and we are said to compulsorily use a scripting language as well so I thought change colors and stuff would be an easy project
Fair enough. I don't think it's too difficult
It's more like a favourite theme saver
Have a look at the examples. It's not that bad to use localstorage
Funnily enough they have an example specifically demonstrating a colour being saved
But it's using <option> full of colors its little different
I couldn't find a solution for my one anywhere
My color is stored in var color not using any <option>
Didn't check mdn yet though, will check there now
I don't have to use PHP
@proper hinge I could use something different, what would you recommend?
Python 😄
lol
That's what I want to use, but I don't believe I could get a django instance running on a shared web hosting site
I did look into that as much as I could but didn't find an acceptable answer
I agree.
Well if you're not so invested in it yet, don't use that shared hosting
Otherwise I don't really know. I'm not familiar with what restrictions the service you're using has
And not familiar with PHP. But if they disabled that feature then my guess is you can't do it
Probably not without some hack at least
Just a guess though
Yeah, I agree. Unfortunately, had this hosting for a while. Not sure what I would use instead
I've only used DigitalOcean in the past
and they're talked of highly from what I've read
Not saying you should use them automatically
but just consider it
and research your options
there are a lot of companies out there with competitive pricing
But you'll basically have a machine you can install whatever you want on
Thank you
@proper hinge couldn't find it, can you give me the link
@frank spade You don't need it, If you app works with your code it's okay. Pylint is just the python Grammarly (okay, not at all, it can't change your code tough, you'll need another lib to do that). But that just will say if your syntax is doing well.
@little shuttle primary key is a database concept, relations is a Django concept
@native tide https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
@polar vapor thanks
That was exactly what I was looking for, it's very simple and easy to understand. Using cookies instead is way to hard than this.
You're welcome
I finished it correct me if I am wrong
`document.body.style.background = localStorage.getItem('savedcolor');
function savecolor()
{
localStorage.clear();
localStorage.setItem('savedcolor',document.body.style.background);
}`
is localstorage.clear(); pointless because it's just overwriting the var savedcolor?
It shouldn't overflow if I use the same variable so I think clearing storage is pointless
Yes, I would think that is is unnecessary to clear
anyone here with angular experience? I've posted something on stack overflow
Hi, i have 2 nginx servers, 1 that goes to the public, and another one on my mass storage system.
Im using proxy_pass on the public one to connect to the mass storage, but if a request takes more than a minutes and a half, my router completely blocks the ethernet port the public nginx server is connected to.
Anyone has any idea of router settings i could look into or other stuff? or an alternative to proxy_pass?
The router logs are not helping either, it's just a bunch of this https://5124.mywire.org/HDD/SS/02:10:16_24-09-2019.png
(192.168.1.40 is the mass storage IP).
(Ping me)
So I was watching tutorials of how to connect database to python and many were using sqlalchemy, but the I found one that just uses SQLite3 import
What’s the eve for of using sqlalchemy?
Sql alchemy aims to abstract the actual sql away from you and let you manage your data indirectly through classes. If you're just beginning, I'd recommend sticking with just sqlite3 without sql alchemy
Yeah is an ORM.
That allows you to manage data as an object instance.
Because Python is POO.
Is not the only one that exists, but is the most common one with flask.
And also you don't need to do normal queries like "SELECT * FROM [table] where [conditional]".
You can use built-in methods from the ORM like "query.find_by(property=value)".
ORM (using database elements as objects) are useful for backend API too, because with the object you can make easier a API Schema, so you can jsonify the data in a organized way and more pythonic one too... Good practices.
@misty dune and @rigid laurel Great hacking!
How does python backend (flask? I dont really know) compare to php counterpart?
I am considering moving from phpmyadmin and I'd like to write in python so, I dont even know what exactly I'll use but I wanna know advantages :3
Use: a local job board app
(tag me I might forget I asked here :D)
@ornate frigate if you want to do backend with python, you'll have to use a framework that is specialized for making backend
you got few choices
flask,djago,pyramid ...
corey schafer has tutorials on both flask and django
Everytime i try to use flask-sqlalchemy this happens
It doesn't recognise my db
does it throw error when u run the file?
you have a url pointed to a view that doesn't return what it should, im gueesing
@flint breach Nvm fixed it!
I'm stuck with this Instance of 'SQLAlchemy' has no 'Column' member
I get those as problems
@hollow glacier how are you running the app
@vagrant adder python app.py
in the teminal
worked like a charm an hour ago
Then this happened
Hi guys, I have a quesiton
regarding Django
is anyone experienced with Django?
I am looking to create an application that allows users to create a profile, and create/edit tasks within that application as part of a business that I'm running. My question is:
Would I need to create a user authenthication application in the process? (so that users can log in and create/edit/delete posts) Or should I just extend the built in user authenthication application?
Is it possible to print html input as JavaScript output just by using html css java (and not any other stuff like PHP)
I want to document write ( input type="text" ) just by html and java
@proper hinge can u give me a ✋ here
Sorry, not right now. Maybe someone else can help.
For what it is worth your question isn't very clear. I think it would be helpful to try re-phrasing it
How to document.write user inputs of (<input type="text">)
(Only using html and java)
get the element with javascript. For example, you can use document.getElementById() if the input element has an ID
then you can do .value to get the contents of the input
Also, don't shorten JavaScript to Java. It's not correct. They are two different languages.
Hello everyone 🙂 What is the actual proper way to create and manage user accounts in Django ? Should i use built in model user or create a separate model table for all users with columns for their names, emails and passwords ?
@proper hinge yeah I am actually lazy to type but I never mispronounce them while talking
Hi guys, currently got this code
connection = sqlite3.connect(os.path.realpath('app/database/xxxxxxxxxx.db'))
cursor = connection.cursor()
# Query that select all active sweepstakes.
cursor.execute("""
SELECT *
FROM sweepstake
WHERE active = 1
""")
# Fetching.
sweepstakes = cursor.fetchall()
for sweepstake in sweepstakes:
cursor.execute("""
SELECT *
FROM chatMessage
where sweepstakeId = ? AND promoted = 1
""", str(sweepstake[0]))
r = cursor.fetchall()
return r```
def keyword():
return render_template('keyword.html', fetch_messages=database.fetch_promoted_messages(), sweepstakes=database.fetch_sweepstake())```
the problem here is that it iterate once trough the for loop and returns it so it always stops after the first return, how can I avoid this?
keyword.html
<h2>Sweepstakes</h2>
<ul>
{% for keyword in sweepstakes %}
<li>
{{ keyword }}
</li>
{% endfor %}
</ul>
</section>```
It displays this on the keyword page
This is the chatMessage table
it basically skips the 'kip keyword' message
How to update a framework
And is there a big differences between django 2.1 and 2.2
try pip install flask-sqlalchemy
what's the best framework for developing a back-end in python? I am planning to have my site (made with angular) and my discord bot (discord.py) connect to it. I am guessing Flask or Django. But what's best for a back-end, and if there is something better what is it?
flask and django are really the best out there
which would be best for a back-end?
most probably.
or it's gonna render html internally
api, it's not gona do any html.
aight
just get and serve data to the site and bot.
flask is most probably gonna be best option
okay thanks 😄
also, flask-restless goes hand in hand with flask-sqlalchemy
it literally makes the api for you
but some prefer flask-restful
restful is more of doing api without database and/or very very small and simple models
hm, I dont think I will be doing any databases. mostly just storing results from the bot until the site asks for it. and maybe some other stuff.
then flask restful is going to be more optimal
okay 👍🏻 will look in to it.
i mean, you can build all the routes on your own but those libraries are made to automate that
I am a programmer if somebody has already done it, I use their code!

I'm building a JSON websockets server using asyncio but I'm unsure if I should use StreamReader.read, StreamReader.readline or StreamReader.readuntil to read data received from a client, what should I use?
You probably want to receive all the data right?
So just read() will read until EOF
ah well, it didn't work at all(it got 2 payloads altogether)
have you printed the data to have a look for yourself?
Does it look like valid JSON to you?
It's supposed to be 2 different messages
How is the client sending data to you?
I made this test to see how data would be sent to a client(this is a client)
And this is the server, the callback that builds clients upon connection
this is how the server sends data
I set the read value to 100 and it worked but does this limit the size of a payload?
You may need to use write_eof so it knows the end?
I looked at your code I'm not sure why two payloads were received simultaneously anyway.
Cause you only write once
And setting the value for reading doesn't limit the payload. The rest of the data will still be in the buffer
aight I think I'm gonna set the limit to 100
because after calling write_eof the writer closes it seems :/
Yeah I suspected that may happen actually
I don't have enough experience with this
I would think that you'd need the client to give you the length of the data it's about to send you
so you'd read the first few bytes to get the length
and then read as many bytes as the length is
I set up a delimiter instead, but thanks anyways
Oh right, that works too
Downside is you can't have the delimiter be part of JSON data ever
the delimiter is appended when we're about to send data already dumped as a string and then decoded as bytes
Then when the client reads it, it only takes off the last byte of the message
ez
and it works good
hello
I have tried - and so far failed - to get the body text of an email from an IMAP server in a quoted printable format using either the imaplib
or the imapclient library
I currently have a script working on standardized emails and it uses offlineIMAP (https://github.com/OfflineIMAP/offlineimap) to get a local copy of the email text that it then can parse
as offlineIMAP is iffy to get to run under Windows, I'm trying to integrate the IMAP access into my script
sadly, all the fetch options I have found and tried that give me the source code of a mail are not encoded in quoted printable and so have semi-random line breaks messing up the parsing of the mail text
I have tried to have a look into the offlineIMAP library, but sadly I'm a noob when it comes to github and the inspecting of libraries
so if someone either knows how to get the body text of an email in from an IMAP server in quoted printable format or who knows how to extract the information from the offlineIMAP library... any help is appreciated
Does this help? https://imapclient.readthedocs.io/en/2.1.0/
Looks like a wrapper that handles parsing for you
i have made a bokeh plot and i want to put it in my website
is copy pasting the source code from the bokeh plot an option?
hello?
Like copying and pasting it here you mean?
I think the hastebin could handle that, yeah. You'd just have to change the file suffix the site gives the URL when you save it so that it shows the proper highlighting
no i mean in a HTML file @near ridge
Hey so Iam making a simple django website
the homepage would be <domainname>.com/
the login and signup would be <domainname>.com/login/
the thing I want to make the homepage only visible to the user that have register. So how do I redirect the first time user to the signup form?
when they goes to the <domainname>.com/
or does my url tree is not a good practice to be use?
@restive bloom that was the first docs i consulted, sadly while it documents the fetch commands, I couldn't find information on valid argument - i.e. what I can fetch
I also couldn't find a command to return a list of fetchable items from the IMAP server
hi guys, i have a question regarding Django (+ DRF)
essentially, i've been trying to build a simple REST API for a todo list for learning, and i've hit a slight problem with the User model
all I need is to change the identifier of a user from 'username' to email, however it seems like I would need to create a new model (let's call it Account), based on this doc (https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#a-full-example)
is this the only way? i cant imagine everytime someone starts a Django project needing to rewrite an entire User model (and the Admin as well)
I suspect you will have to, the docs seem quite insistent on that manner. You will not have to make a custom manager or anything else, just a subclass, settings change, and adjusting the USERNAME_FIELD class variable
Interested to know how people set up user and group permissions in their flask app, could some shed some light on this..?
https://flask-user.readthedocs.io/en/latest/index.html Maybe you could use this? I can't vouch for how good it is, but it sounds like what you want on paper at least.
791 stars on github
But no releases since last year.
Thing is I'm using flask-login already, and ideally I don't want to use a dependency
I've seen things like Flask-Paetorian, Flask-Permissions and Flask-Allows but I'd rather create my own solution
Well, it's not a simple project if you want a solution that's flexible.
But that depends on your application.
At my last job we had our own permission system that decouples users, roles, services, resources and resource groups.
The problem is a lot of these libraries don't work with QUart because of the ASync nature
I've made a login system and a small todo app. I would like to try to merge them together so that multiple users can use the app. I've tried to figure out how to give a table for each user but I'm not sure if that's the way to do it. Any ideas?
Been reading through this article: https://heap.io/blog/engineering/structure-permissions-saas-app
So you’re building a SaaS product and you want to serve real customers and start making those fat enterprise bucks. Great! Now you need to support weird stuff you’ve never heard of before like LDAP, SAML, SSO, and… RBAC. What is RBAC? Role Based Access Control is a syst...
@hollow glacier You don't want a separate database table for each user.
@open forum Are you able to share any examples or is it NDA..?
@hollow glacier You probably want to have a user table with one row per user.
@pseudo fjord Talking about it in the abstract is not a problem.
@open forum maybe I should assign each user a key and then set that key to each todo item?
Maybe use the primary key?
@hollow glacier I'm not sure how you've modeled it, but one way would be to have a todo-list table, with one row per list, and then have an owner column in that table, which contains the ID of the user that owns that list, and then have a different table with todo items, and have a list column in that table with the ID of the list the todo item belongs to.
This is my current user object: https://github.com/Netroxen/evie.cms/blob/master/evie/auth/user.py I have a simple roles attribute assigned to the user, should this take a single group name, multiple roles or a single role that is connected to a group..?
@hollow glacier Then you can make a query like "SELECT * FROM todo-item WHERE list = 123" to get all the todo items in one list.
Or "SELECT * FROM todo-list WHERE user = 323" to get all the to-do lists of a user.
My understanding is that a user should have multiple roles assigned to him, and these roles are associated to a group or multiple groups
@pseudo fjord The way it worked for us is that each API endpoint is a "service", and services can be organized into a hierarchical service-group tree. So a service-group can contain individual services or one or more service-groups.
Then a role has one or more services and/or service groups.
Individual entities in your system are resources, and they can likewise be organized into a hierarchical resource group tree.
Then finally, a user is associated with one or more roles, and one or more resource groups.
so you can check if a resource or multiple resources are children of a parent group or so on..?
Ahh I see
Yeah. We had users that were associated with different organizations, and different user types within each organization.
and why do you seperate the resources and auth on the user..?
what's the benefit, does that not add more complexity..?
Well, you could have for example a TRADER role, and you could have users in multiple different organizations that are all traders.
They all need the same access profile with regards to the API.
But, they belong to different organizations, so they shouldn't have access to the same data.
Ahh ok, I guess that's a project specific requirement then
So they have the same role, but different resource groups.
Makes sense
And likewise, within an organization, you have TRADERS and like... BACKOFFICE_MANAGER or something.
They should have access to the same organization data, but have different service access profiles.
A trader can trade, a backoffice manager can do... Other things.
Sorta, I suppose.
Gawd, I mean the other option is to fork one of these libs and make it work with Quart but the extra workload is... not wanted XP
But yeah, I built stock exchange systems, so maybe it's the high end of complexity requirements for a user access system.
Man sounds like a recent project I had to work on creating a planning permission system for a hospital network, was a permission headache.
Different subsidieries and private associations that had different groups, permissions and SSO requirements, gahhhh
But that was developed in Plone, so a lot of the permissive system is already pretty strongly configured
anyone know generate a quoted-printable string of an email from an IMAP server?
I can grab the email through this code:
import email
import imaplib
connection = imaplib.IMAP4_SSL("somehost", 993)
connection.login("someuser", "somepw")
connection.select("Cabinet")
typ, mails = connection.search('EXISTS')
mail = connection.fetch("1", 'RFC822')[1][0][1]
test = email.message_from_bytes(mail)
print(test)
connection.logout()
the problem is that there are random line breaks in there as it's not formatted in quoted-printable
Hi everyone! Could really use some help here. (Django) My model objects for the model 'Writeup' aren't showing up in my template. My posts one does though.
Model:
template:
view:
objects:
did you do migration on the db?
Yeah
just did again to be sure
I'm sure it's something small but I'm just not sure what
ok nvm I fixed it. It was because WriteUpView() was using the generic view "TemplateView" instead it should've been using "ListView"
nice
Quick question, is it possible to temporarily register a route in flask for the purpose of making an @native vessel.before_first_request form..?
I want that the first time my app starts, I check my database if the app has been initialized, if not I want to direct the user to a template and form where they can enter some default settings...
well, @app.before_first_request is not a route, it's a decorator to a function that will do something when user first visits the site
it's not meant for rendering anything
if you are making a login/logout system, use flask_login
can we customised form without using crispy-form?
im making simple web, so using bootstrap is lil bit overwhelming
Django?
yeah man
Yea u can
so I have a problem where
{% csrf_token %}
{% for detail in form %}
<div class="box">
<label>Name:</label>
{{ detail }}
</div>
{% endfor %}
<input type="submit">```
Example from my repo
but when i use the label, every box will have Name : label
then?
im not that good at reading github, so many file to look for 🙂
No I sent the html file
The link goes to the html file
Which has a form
Complete flexibility on styling
owh, get it... should do {{ form.username }}
error as an example?
so by putting .errors at the end will raise a ValidationError without need to change on the backend?
ik, but I mean you don't need to type return ValidationError("Error") on the views.py right?
aite, would look after that... thanks for the help man
👍
appreciated it
have a nice day!
youu too
Hi, I am trying to group count metrics per hour for given day, however, it only goes up to 22 instead of 23, here is my sample query set: https://gist.github.com/gnud/3a17ce219b2a44e228c9aaf6bec0bad0, is it because it starts from 0 or something in d1 or?
sample output: <class 'list'>: [(6, 0), (7, 1), (7, 2), (7, 3), (7, 4), (5, 5), (7, 6), (8, 7), (9, 8), (6, 9), (10, 10), (7, 11), (9, 12), (6, 13), (10, 14), (7, 15), (9, 16), (7, 17), (5, 18), (7, 19), (6, 20), (9, 21), (7, 22)]
created__lte=d2, created__gte=d1 gives me the same result
Even this doesn't work: created__hour__gte=1, created__hour__lte=25, created__day=23
Whoops, found the error, in the fake record generator, I was missing +1 for the hours range 😄
@vagrant adder Already using Flask-Login. I want the user to be met with a template / setup page the first time the application runs, this should be shown before the user visits the index page on the first request...
Something like omegle?
Well, you can check if the user is authenticated
If not, yeet him the form
Yeah this is the tricky thing, because this is a one-time setup which asks the user to create an admin user and configure some app settings, after which the admin can log in and users can register
Think of it like a quickstart setup for the administrator the first time the app runs
The problem is, im not sure how to set this up
My suggestion would be to decorate your views with something that checks to see if the site has been set up yet, and if not redirect them to the set up view
Then in your set up view, set some flag to true
@pseudo fjord
yeah, making an admin user is usually done manually
or using some secret route
something like baselink/admin/super/duper/secret
@rigid laurel Cheers mate, was thinking along those lines. Is there a way I can decorate all my views globally without having to do it for every view
Does that work on the '/' route for all views
Whenever I've done similar things in the past I've just put the decorator everywhere - although I feel like there certainly ought to be a better way
actually, are you sure that @app.before_request isn't what you want? https://stackoverflow.com/questions/14367991/flask-before-request-add-exception-for-specific-route
I'm working on a proof of concept situation, and I need to set up a really insecure email inbox that I can access from a python script.
Can I use a session variable in flask to store the users primary key so I can use that in queries in other tables?
Or is there a better way to get the users primary key so I can use it to query other tables?
Anyone has a good guide how to deploy a flask app on an ubuntu server?
@primal grove
flask_mail
@hoary spruce
https://youtu.be/goToXTC96Co
In this Python Flask Tutorial, we will be learning how to deploy our application to a Linux Server from scratch using Linode. If you would like $20 of free c...
@vagrant adder flask_mail only sends
Django?
Well, remove python folder and put server.py one step upper
Well, it's virtually impossible to do that then
Yeah
That's how flask works
You isolated Flask instance and can't link anything
This is a project of mine
I instantiated Flask object in app/__init__.py
And every folder is in that folder
Yes, in level with other and static
It's not
That's how every framework
You can't isolate an app instance in it's own folder and expect to import anything
👌
What
Nah, not in here
im using @login_required for my homepage, this thing is how do I redirect first time user to the signup form when they press the homepage link?
doing it with django
it automatically does that i belive
Hi all
I have an odd problem
At some point my Django application stopped recognizing os path
For example, in settings.py I have
DEBUG = os.environ.get('DJANGO_DEBUG', False)
And in activate.bat (which is venv settings file on windows) I have all the settings including
set "DJANGO_DEBUG=1"
I'm not sure what I did because I can't remember tinkering with those settings for some time, and it used to work fine, and now I can't launch the application because I have set my secret key the same way, through environment variable.
Can someone please help me find the problem?
Can you paste your activate.bat ?
@marsh canyon no it doesn't if I press the homepage as a non-user, I will get page not found 404
Well just don't display the link to the home page if user is not authenticated
That should solve it
@primal drift
I'm currently codin the part to delete a todo item. Right now I'm basically doing this:
@login_required
def delete(id):
task_to_delete = Todo.query.get_or_404(id)
try:
db.session.delete(task_to_delete)
db.session.commit()
return redirect('/task-manager')
except:
return 'There was a problem deleting that task'```
But wouldn't that be insecure since anyone that's logged in could just type domain/task-manager/<random number>
But wouldn't that be insecure since anyone that's logged in could just type domain/task-manager/<random number>
And just delete something
Any ideas how to make it more secure?
add in there
if task_to_delete.author is not current_user:
return redirect('/somewhere', warning="we don't do that here")
just check if author is current user
@vagrant adder Oh, is author a feature of flask_login?
nope, that's a reference to an author in your models.py
i'm guessing at least
@hollow glacier can you paste your models.py?
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True)
email = db.Column(db.String(50), unique=True)
password = db.Column(db.String(80))
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
content = db.Column(db.String(200))
isCompleted = db.Column(db.Boolean)```
how are those even connected lol
new_todo = Todo(user_id=current_user.id, content=form.content.data, isCompleted=False)
Was the best way I could figure out myself
I'm still new to all of this
So it's probably a bad idea
But it works
¯_(ツ)_/¯
take a look at this:
https://www.youtube.com/watch?v=cYWiDiIUxQc&t=210
In this Python Flask Tutorial, we will be learning how to create a database using Flask-SQLAlchemy. SQLAlchemy is a great tool for working with databases bec...
not really how you link users
Oh
in your project, you'll manually need to query every user using Todo's user_id