#web-development
2 messages · Page 21 of 1
all this stuff is new to me so I'm excited; just wanted some insight other than what I read on google.
Yea think of JavaScript of adding dynamic content to your website like animations (although css can do some too nowadays) or making a webpage that doesn’t have to “refresh” to get new data. Python fits in as the backend or server to serve your website it’s content and JavaScript will do things to that content.
I see, thanks for the clarification... Python is the engine in the car.. but JS is the steering wheel and the Radio.
while CSS is the appearance? lol
Not great when it comes to analogies but yea that works haha
I have a quick question
When I do py manage.py shell I can't type anything after
Why is this?
is it working?
might need to verify python and django is installed and working.
maybe make sure you are using the python with the django installed to run it
python -m pip list```
Hey, how would I get this working with namespaces?
# Provide a way for a user to revoke/unrevoke their tokens
@app.route('/auth/token/<token_id>', methods=['PUT'])
@jwt_required
def modify_token(token_id):
# Get and verify the desired revoked status from the body
json_data = request.get_json(silent=True)
if not json_data:
return jsonify({"msg": "Missing 'revoke' in body"}), 400
revoke = json_data.get('revoke', None)
if revoke is None:
return jsonify({"msg": "Missing 'revoke' in body"}), 400
if not isinstance(revoke, bool):
return jsonify({"msg": "'revoke' must be a boolean"}), 400
# Revoke or unrevoke the token based on what was passed to this function
user_identity = get_jwt_identity()
try:
if revoke:
revoke_token(token_id, user_identity)
return jsonify({'msg': 'Token revoked'}), 200
else:
unrevoke_token(token_id, user_identity)
return jsonify({'msg': 'Token unrevoked'}), 200
except TokenNotFound:
return jsonify({'msg': 'The specified token was not found'}), 404
I'm having trouble figuring out how I would make that to a class and get the <token_id> from the url part to be passed to a function?
I think I got that one already, but ideas on this error?
TypeError: token_in_blacklist_loader() missing 1 required positional argument: 'callback'
Code itself:
# Define our callback function to check if a token has been revoked or not
@jwt.token_in_blacklist_loader
def check_if_token_revoked(decoded_token):
return is_token_revoked(decoded_token)
is_token_revoked:
def is_token_revoked(decoded_token):
"""
Checks if the given token is revoked or not. Because we are adding all the
tokens that we create into this database, if the token is not present
in the database we are going to consider it revoked, as we don't know where
it was created.
"""
jti = decoded_token['jti']
try:
token = TokenBlacklist.query.filter_by(jti=jti).one()
return token.revoked
except NoResultFound:
return True
Okey, fixed it.
What's wrong with this?
Traceback (most recent call last):
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/sm/PycharmProjects/REST-API/app/__init__.py", line 32, in <module>
api.add_namespace(auth_ns)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 425, in add_namespace
self.register_resource(ns, resource, *self.ns_urls(ns, urls), **kwargs)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 264, in register_resource
self._register_view(self.app, resource, namespace, *urls, **kwargs)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 287, in _register_view
resource_func = self.output(resource.as_view(endpoint, self, *resource_class_args,
AttributeError: 'function' object has no attribute 'as_view'
Looks like you’re trying to call a function of a function which has no as_view method
Hey I just had a quick question in regards to Flask and a just basic counter function that counts the amount of times it has been run but when the website has a lot of traffic the counter jumps all over the place
def counter():
counter.counter += 1
counter.counter = 0
Sorry I’m on mobile haha
Could you clarify what you mean by all over the place? Is it not sequential?
Yeah it’s not sequential
Obviously when a lot of traffic on the site the console spams quite a lot but yeah the numbers were for sure not sequential
How is your website hosted? Is it on nginx or Apache?
Or app*
And how is the counter variable being stored? Database? Browser memory?
Cache?
I don't know what is wrong with this so it gives an AttributeError.
auth_controller:
from flask import request, jsonify
from flask_restplus import Resource
from flask_jwt_extended import jwt_refresh_token_required, jwt_required
from app.main.service.auth_helper import Auth
from ..util.dto import AuthDto
api = AuthDto.api
user_auth = AuthDto.user_auth
# TODO: Fix the AttributeError.
@api.route('/login')
class UserLogin(Resource):
"""
User Login Resource
"""
@api.doc('user login')
@api.expect(user_auth, validate=True)
def post(self):
# get the post data
post_data = request.json
return Auth.login_user(data=post_data)
@api.route('/refresh')
@jwt_refresh_token_required
class RefreshToken(Resource):
@jwt_required
def post(self):
return Auth.refresh_token()
@api.route('/token')
class GetTokens(Resource):
@jwt_required
def get(self):
return Auth.get_tokens()
@api.route('/token/<token_id>')
@api.param('token_id', 'The token identifier')
class ModifyToken(Resource):
def put(self, token_id):
return Auth.modify_token(token_id)
Could someone give me pointers?
@hollow flower , I haven't worked too much with flask_restful, but I bet you'll find the answer in this doc http://flask.pocoo.org/docs/1.0/views/
in particular, how to set up views
I have no views, yet other ones work fine.
Sure, but it's probably opinionated and requires a setup you're probably missing somewhere
Which endpoint is it thats failing?
I could only guess that what you're returning is not valid (e.g. the Auth.<functions>)
The failing end-points code is the one pasted above.
hey guys,im having a lil issue with image loading in django
title = models.CharField(max_length = 64)
image = models.ImageField(
blank=True,
upload_to = 'post_images'
)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
posted_by = models.ForeignKey(User, on_delete=models.CASCADE)```
my model
i made the Post through the admin portal and did put in an image,but when i want to display the Post ,the image dosent appear and when i open it in a new page,it throws a 404
but i do have the image inmedia/post_images/
any idea what im missing?
nvm i fixed it
a lil typing mistake in the url pattern
I need some help with a simple Flask error. I'm using CGI and Flask. This is main.html.
`<html>
<h1>Form Input test</h1>
<form name="search" action="/cgi-bin/main.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form>
in your test.py
</html>
`
This is main.py
`from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
app = Flask('name')
@app.route('/')
def home():
return render_template('main.html')
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)
if name == "main":
app.debug = True
app.run()
`
I'm getting a 500 error.
Is there anything wrong?
show me your request
@uneven jasper Please don't advertise your question in other channels.
Sorry
wouldnt that be running on some port that isnt port 80?
thats the error you got?
but you havent imported jinja im confused
You just need render_template for jinja
I don't know why it'd give me that if I didn't have jinja
I imported jinja and now it's saying the page refused to connect
Make a folder called templates
And put main.html in there
I have problem, which is kind of odd.
Traceback:
[2019-03-09 17:50:44,105] ERROR in app: Exception on /auth/login [POST]
Traceback (most recent call last):
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 325, in wrapper
resp = resource(*args, **kwargs)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/resource.py", line 44, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/sm/PycharmProjects/REST-API/app/main/controller/auth_controller.py", line 22, in post
return Auth.login_user(data=post_data)
File "/home/sm/PycharmProjects/REST-API/app/main/service/auth_helper.py", line 46, in login_user
access_token = create_access_token(identity=data['username'], fresh=True)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_jwt_extended/utils.py", line 141, in create_access_token
return jwt_manager._create_access_token(identity, fresh, expires_delta, user_claims)
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_jwt_extended/jwt_manager.py", line 476, in _create_access_token
json_encoder=config.json_encoder
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_jwt_extended/tokens.py", line 67, in encode_access_token
'type': 'access',
TypeError: unhashable type: 'list'
Not strictly Python-related (possibly strictly unpython related) but any advice for learning how to learn enough javascript to make better Flask/Django apps? Are there any tools that provide shortcuts either in the Python language (or jinja2/django templating), or in the PyCharm IDE?
@hollow flower Any more context? This looks familiar
what are you trying to do exactly?
Create access_tokens with flask-jwt-extended, and use username as identity.
Can you show us the source?
@staticmethod
def login_user(data):
user = None
try:
# fetch the user data
user = User.query.filter_by(username=data.get('username')).first()
except Exception as e:
print(e)
response_object = {
'status': 'failed',
'message': 'Something odd happened.'
}
return response_object, 400
if user is None:
try:
user = User.query.filter_by(email=data.get('username')).first()
except Exception as e:
print(e)
response_object = {
'status': 'failed',
'message': 'User is not known'
}
return response_object, 401
if user and user.check_password(data.get('password')):
test_data = json.dumps(data)
print(test_data)
access_token = create_access_token(identity=data['username'], fresh=True)
refresh_token = create_refresh_token(identity=data['username'], expires_delta=timedelta(hours=1))
response_object = {
'status': 'success',
'message': 'Successfully logged in.',
'authorization': {
'access-token': access_token,
'refresh-token': refresh_token
}
}
return response_object, 200
This is the source for it.
It's the login_user from auth_helper.
Hmmm
What's the name of file that function/method is in?
access_token = create_access_token(identity=data['username'], fresh=True)
So this is the line in that code where it starts to trip up, if I'm reading that traceback correctly. I'm trying to figure out what list it's talking about
What is data['username']
Is that just a string?
>>> {list(): "Lists aren't hashable, dork!"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>```
Are you passing a list anywhere it's either getting used as a dictionary key, or between processes (e.g. to a worker) or anything?
Check this example out too, maybe.
https://flask-jwt-extended.readthedocs.io/en/latest/tokens_from_complex_object.html
data['username'] is basically a string, from json request.
basically a string, 🤔
I noticed before you did
username=data.get('username')).first()
Which suggests to me that data['username'] isn't a string.
@hollow flower
If it's a list, it would explain why that line of code is giving you the unhashable type error.
Oof, that's probably my problem.
i installed xdebug to profile stuff with php, it turned on some stack trace shit that only puts the first useless line into error.log instead of the good old error messages
i disabled everything to do with it in php.ini and restarted webserver but it still does it
how do i get rid of this shit 
@prime ridge It's a dict apperently.
'dict' object is not callable
Huh?
@heady basin This is a python server...
But you probably didn't edit the correct php.ini file
I want to print the entered data from this html page into the terminal. I'm using flask and cgi. My html
`<html>
<h1>Form Input test</h1>
<form name="search" action="/cgi-bin/main.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form>
</html>**This is main.py**
from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
app = Flask('name')
@app.route('/')
def home():
return render_template('main.html')
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)
if name == "main":
app.debug = True
app.run() `
Please use the ` for send code
Sorry about that, It's impossible to add paragraphs.
Shift + Enter
Ok thanks
No
Problem :)
I am pretty sure app = Flask('__name__') is supposed to be app = Flask(__name__)
Please send me a screen shot of your code
It reloads to this url .http://127.0.0.1:5000/cgi-bin/main.py?searchbox=hello
Ok
python file
html
You need to make another endpoint
?
Which would require you to make another function
@app.route('/search')
def search(request):
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)
Whoops...
I forgot it's three back ticks
What i'm trying to do is make randomly generated forms for people to take and then the data get's sent to me via email.
Should have I used the search input type?
Are you talking about your html?
Yes
You're html is fine
Your code is not
You need to make another endpoint/route for where your search form will submit to
Vc?
I dont know.
I'm trying to print it to make sure I can store the input in a variable.
Once I get it in a variable I can use it accordingly
I understand that
But you still have to create a new route to do that
Right now there's issues in your code that need to be fixed for that to happen
Oh, so the form and searchterm should be in a route so they can loop?
What loop
So they can be executed more than once?
Yeah you don't need a loop to do that
Okay now you need to make sure that your html form action attribute is set to that route
Ok
Alright, I got this: builtins.TypeError
TypeError: search() missing 1 required positional argument: 'request'
I need to see the code
Can you give me the full stack trace as well?
Nvm
Get rid of the request in def search(request):
Done
Does it work now?
Indentation error on form variable. I removed the indent and It gave me a syntax error.
You need to make sure you either using all spaces or all tabs
I'm using tabs
Make sure everything is tabs then
I removed indentation from everything and re indented. Still got an error.
Copy and paste your code in to chat
`
from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
import jinja2
app = Flask(name)
@app.route('/')
def home():
return render_template('main.html')
@app.route('/search')
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)
if name == "main":
app.debug = True
app.run()
`
Im getting an error at line 13. At the form variable.
You need to have def search(): in there
Between @app.route('/search') and form = cgi.FieldStorage()
I said to remove request not the whole line haha
Oh! lol ok
builtins.TypeError TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
Add return render_template('main.html') at the bottom of the function
the search function
See if you type something if it still works
Okay
So I typed in "None" the first time. Apparently it means something because even when I reset it, it prints 'none'.
Yeah so you are using some cgi library when your application is running in flask
It's fundamental how cgi and flask work
?
Get rid of the line form = cgi.FieldStorage()
then change searchterm = form.getvalue('searchbox') to searchterm = request.form['searchbox']
Yeah cgi is just a completely different technology then what flask uses
Cgi works on file basis while flask is wsgi application
werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'searchbox'
That's a weird error.
Did you submit to the form?
Yeah
It matches the name though.
jk you should of switch it too request.args.get('searchbox')
request.form is if your submitting a post request
But you are doing a get request
Nice
Thank you for your help!!
No problem my dude
Gosh time flies when your fixing... stuff.
If left unspecified, do users submitting requests to a Flask application have any say over what type Python interprets a parameter as?
Here's my example.
b = request.args.get('b', 0) # Note I did not specify type=int, so the server may assume str```
These should both be type=int for the calculator to function
It seems that, when used normally, the type will default to str
but I'm wondering if the user (e.g. a malicious one) could somehow make the server parse it as a list, or some other type
@prime ridge , the rule is to never trust the user input
Of course that's the rule
They could possibly take advantage of Python's duck type and could possibly perform malicious acts that will break your application
Yeah, that's exactly what I'm getting at. But is it ACTUALLY possible, is the question
I wouldn't write sites that way
If Flask handles it then it isn't possible.
e.g. if flask always defaults to a string
Ok, sure. Why don't you write some tests then to confirm if thats true?
I don't know how
I know how to write unit tests
I don't know how I'd forge a GET/POST request that tricks Python into typing something other than a str
The question to begin with is whether that's possible.
Use postman or curl
I don't know enough of the internals, but its better to test or read the source code itself
I did, but I stopped when I didn't know how to specify type in a request. I'd imagine there might be a header for that.
I know you can specify content type, but idk if that's just for any field
I think that's more for, like, whether you're sending json/xml/etc
Flask has an option to get a list from a request, but you have to explicitly use that function and it'll check for duplicate parameters
e.g. item=1&item=2 == [1, 2]
So I'll give you a simplified example.
Lets say your application is sending JSON which can have different types and your function was expecting a string, but supposedly could also get a number
Flask will not deserialize it to correct the term
type*
that YOU expect, it will deserialize it whatever was sent
its up to the developer to handle the different types of JSON payloads at that point
Yeahhh, lemme check and see what happens if I pass a json int when the type is unspecified
Its why we have libraries such as https://python-jsonschema.readthedocs.io/en/stable/
Looks like by default flask doesn't parse arguments from json. I guess that's a behavior you have to code manually
.get_json()
okay, so if you DO that though
if request.method == 'POST':
a = request.get_json()['a']
b = request.get_json()['b']
return jsonify(result=a+b)```
Sending
{
"a": "1",
"b": "2"
}
``` returns `"12"`
but sending
{
"a": 1,
"b": 2
}```
returns `3`
Yup.
Interesting. I know some really badly coded python sites where, were it possible to specify type on the inputs like this, it would be catastrophic
I've read code with really bad input validation that uses iteration to validate input that goes directly into an SQL query where, were you to give it a list, you could bypass that check entirely
Ha, I wish. It is a company I code for, but they're too stubborn to replace this awful legacy code.
Some day...
Regardings this (https://discordapp.com/channels/267624335836053506/366673702533988363/554002134106898432), I still need help with it
Ok
this might seem like a crazy request idk
but im trying to run flask and discord in the same application
this is what i have so far
from flask import Flask, jsonify, request
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
app = Flask(__name__)
#Discord Bot Loads
Bot = discord.Client()
bot = commands.Bot(command_prefix='--')
bot.remove_command('help')
#Waits for PUT Request
@app.route('/questionData', methods=["PUT"])
def newQuestion():
data = request.get_json()
#Post discord embed
return jsonify(data), 201
if __name__ == '__main__':
app.run(debug=True)
i tried to add on_ready() and bot.run() but the site refused to load
i want to make it so that when it receives a PUT request, it uses that data in the discord embed
@hollow flower the webpage wont load
How are you calling it?
@hollow flower one sec
@hollow flower ```py
from flask import Flask, jsonify, request
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
app = Flask(name)
#Discord Bot Loads
Bot = discord.Client()
bot = commands.Bot(command_prefix='--')
bot.remove_command('help')
@bot.event
async def on_ready():
await bot.say("Ready")
#Waits for PUT Request
@app.route('/questionData', methods=["PUT"])
def newQuestion():
data = request.get_json()
return jsonify(data["answers"]), 201
if name == 'main':
app.run(debug=True)
bot.run("")
Last time I checked, you probably can't mix async code with non-async.
Does the bot log-onto Discord though?
hmmm
#Waits for PUT Request
@app.route('/questionData', methods=["PUT"])
def newQuestion():
data = request.get_json()
#Discord Embed goes here.
return jsonify(data["answers"]), 201
So what's your goal exactly?
to send a message in discord using the data included in the PUT
and for it to send the message right after the PUT
Then your code is wrong. You can return the 201, but you don't need to the data itserlf.
Code the discord embed part.
Just try and see.
And is that bot.run() inside the if __name__ == '__main__': identet correctly?
No.
Ident it.
And try it.
The bot is connected though?
im going to run it through putty to see if it connects
does it need to do anything on ready?
No, but I have this.
@bot.event
async def on_ready():
bot.uptime = datetime.datetime.utcnow()
# Create database connection
#bot.pool = await asyncpg.create_pool(config.postgresql, min_size=3, max_size=5)
await bot.change_presence(status=discord.Status.online, activity=game2)
print(f'\n\nLogged in as: {bot.user.name} - {bot.user.id}\nVersion: {discord.__version__}\n')
this is the error im getting on putty
$ python app.py
File "app.py", line 20
await bot.send_message(discord.Object(id='538511258375159850'), 'hello')
^
SyntaxError: invalid syntax
i dont think this'll work
You're doing it incorrectly. That's not a the proper way to send a message.
what do you mean?
Are you on rewrite branch?
no
FUck
what
where is this send_message from?
Why use discord.py v1.0 (rewrite)?
Reference the tags in the brackets for details on specific points.
• Improved documentation
• Context always passed for bot commands
• New ctx shortcuts
• Robust websocket reconnect logic
• Model-based OOP
• Ability for sub-commands to not invoke parent
• Async checks and events
• Case insensitive command name support
• NSFW channel check support
• Channel category support
• Animated emoji support
• Audit log support
• Webhook support
• Improved activity support
• Memory and performance improvements
• New raw events and functions
• Bot and Cog Template creator
Why not?
Rewrite is stable, but still in active development. It is discouraged to use if:
• You won't keep your library up to date
• You won't keep your code up to date with any breaking changes
• You won't subscribe to news of breaking changes with ?rewrite
• You don't want to rewrite your existing code to be compatible
ok
ill use it for a future project
luna, im trying to get discord.py and flask to run on the same app
Example of correct way of sending a message.
await client.send_message(message.channel, 'Hello')
may i ask why?
so that on PUT it uses the data to send a message in discord
@hollow flower you can use send_message on discord.Object, not really advised, but it's valid
wait, i thought there was some reason you couldn't
it's in async faq, it grabs the id from it iirc
its been working for me
you can't do this in rewrite though
is what am trying to do possible?
it's also not the greatest idea to run both a flask server and a bot in the same process
how would I send a message on PUT then
out of curiosity, why a webserver? couldn't you integrate this directly to the bot?
others will be performing the PUT
again, the data will be put into a message on discord
ah...
wish it was as easy as creating a json lol
so is what am trying to do not possible?
ok
so im testing this on putty
and as soon as i do control +c, it prints "Ready"
so I assume only one can be run at once
Heyo
hi
Your issue sounds like you're attempting to run the blocking start calls for both the bot and the flask site at the same time
basically, yes
It's best if you separate the site and bot into two different processes instead
how would i make a command activate after PUT
Otherwise if you must have it, you need to use non blocking start calls to run them and handle the loop running yourself
With flask though you probs should be avoiding the development server environment which is likely what you're using
If you only want an API, why not take advantage of aiohttp
It's already part of the bots dependency list with dpy
Since you have things already it'll make things a little simpler but you'll still need to read up on how to create the API endpoints with the lib.
And sure you could call discord send message API endpoint but that's a bad idea
ok
If you want to just emit a message and not interact you should use webhooks
hmm
that might be a good idea
i think im going to try to use webhooks
because that would make sense
You don't have to worry as much about ratelimits or the bot API complexity, plus you can still send all the normal stuff: content, embeds, attachments.
Plus you don't have to stress at all about bot accounts or permissions.
It's worth using if it's only meant to be message emitting
@coral sorrel webhook worked btw
attempted to call the discord create message API manually, but didnt work
hi guys anyone familiar with UWsgi and nginx etc etc
right now i am trying to get uwsgi to run as a systemctl service
it works if i run uwsgi --ini ini.ini
Why I-m not getting the emails
Why use Flask-RESTful when you can just do the "normal" views way
Does anyone have experience with websub in Flask?
Traceback (most recent call last):
File "/home/sm/PycharmProjects/REST-API/run.py", line 4, in <module>
app = create_app(os.getenv('BOILERPLATE_ENV') or 'dev')
File "/home/sm/PycharmProjects/REST-API/app/__init__.py", line 27, in create_app
from app.main.errors import bp as errors_bp
File "/home/sm/PycharmProjects/REST-API/app/main/__init__.py", line 15, in <module>
from app.main import routes
File "/home/sm/PycharmProjects/REST-API/app/main/routes.py", line 1, in <module>
from app.main.controllers.websub_controller import hub
File "/home/sm/PycharmProjects/REST-API/app/main/controllers/websub_controller.py", line 4, in <module>
from app.main.service.websub_service import hub
File "/home/sm/PycharmProjects/REST-API/app/main/service/websub_service.py", line 10, in <module>
hub = Hub(SQLite3HubStorage('server_data.sqlite3'), celery, **config.Config)
TypeError: type object argument after ** must be a mapping, not type
But that's how I have done it though.
Then change it to a dict I guess
How?
¯_(ツ)_/¯
Traceback (most recent call last):
File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/sm/PycharmProjects/REST-API/run.py", line 2, in <module>
from app import create_app, ma, jwt
File "/home/sm/PycharmProjects/REST-API/app/__init__.py", line 10, in <module>
from app.main.config import config_by_name
File "/home/sm/PycharmProjects/REST-API/app/main/__init__.py", line 15, in <module>
from app.main import routes
File "/home/sm/PycharmProjects/REST-API/app/main/routes.py", line 1, in <module>
from app.main.controllers.websub_controller import hub
File "/home/sm/PycharmProjects/REST-API/app/main/controllers/websub_controller.py", line 4, in <module>
from app.main.service.websub_service import hub
File "/home/sm/PycharmProjects/REST-API/app/main/service/websub_service.py", line 10, in <module>
hub = Hub(SQLite3HubStorage('server_data.sqlite3'), celery, **ConfigDict.__dict__)
TypeError: 'type' object is not subscriptable
Hmm, so close.
I guess this question is better in the web development
I have image directory I'm working with on a live server by atom the images work when I click on the index.thml but don't work when on the live server
the path is standard path to the sub directory where the images are
anyone know of why the live server would not display images ?
It should
@fair pumice Did you tried to get the images with css url()?
Because that doesnt work for live server, for obvious reasons. Because then the live server owner could explore your computer.
The images must be on the same folder as the index.html
Otherwise, it doesnt work
Hey guys. Anyone here know django?
I need to create a painel in my website with django + rest
i see that django admin default painel have the options to create users and groups
and can give acess to each table for each user/group
but i friend my told me that's unsafe and can cause vulnerability
but i see that's a very easy way to do this.
anyone can help me to understand?
@native tide It can be unsafe, if you don't know what are you doing. Django is pretty much safe, because the code is hidden. If that project isnt going to public, then you dont need to worry about safety so much. I suggest you to get started with tutorials on youtube. I got started with Corey Schafer's Django blog tutorial, you get the basic idea, how to create login and register system, views, How to delpoy and other stuff what is needed to get started. @native tide
The most important thing is to turn off the Debugging when you deploy / launch the web app
And Corey Schafer is in this discord server. I think??
Got alot of help from Corey's youtube videos
@elder nebula: Actually, i don't understand when he said that it's unsafe. How can Django can be unsafe with the default admin configuration?
That's don't make sense to me
What django gives me in the default admin configuration it's exactly what i need
but he make me scared telling me that's unsafe
@elder nebula : What do you mean with "if that project isnt going to public" ?
Not exposed to the internet
The project is for a public institution
why i will make a project for not expose for the internet?
If its the default admin, then its pretty safe
With flask-restful, should I be splitting it up into diffrent files inegrated into my blueprints/components or should I make one large file for all of the API?
I would prefare the first one but not sure if is possible by doing it "cleanly"
Django already tells you what you should do before deployment for possible security issues
python manage.py check --deploy
[DJANGO] When I deploy to Heroky, this error occurs
registration/login.html
Request Method: GET
Request URL: https://nameless-lake-14525.herokuapp.com/restaurant/sign-in/?next=/restaurant/
Django Version: 2.1.7
Exception Type: TemplateDoesNotExist
Exception Value:
registration/login.html
Exception Location: /app/.heroku/python/lib/python3.7/site-packages/django/template/loader.py in select_template, line 47
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.7.2
Python Path:
['/app',
'/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python37.zip',
'/app/.heroku/python/lib/python3.7',
'/app/.heroku/python/lib/python3.7/lib-dynload',
'/app/.heroku/python/lib/python3.7/site-packages'] ```
But when I run on localhost, I have made changes in django/contrib/auth/views.py
and changes registration/login.html to restaurant/sign_in/html
The page works at localhost:8000/restaurant/sign_in.html but not on heroku at
www.example.com/restaurant/sign_in.html
How can I make it work?
Requirements.txt
chardet==3.0.4
defusedxml==0.5.0
dj-database-url==0.5.0
Django==2.1.7
django-bootstrap3==11.0.0
django-braces==1.13.0
django-oauth-toolkit==1.2.0
django-rest-framework-social-oauth2==1.1.0
djangorestframework==3.9.2
gunicorn==19.6.0
idna==2.8
oauthlib==3.0.1
Pillow==5.4.1
PyJWT==1.7.1
python-social-auth==0.3.6
python3-openid==3.1.0
pytz==2018.9
requests==2.21.0
requests-oauthlib==1.2.0
six==1.12.0
social-auth-app-django==3.1.0
social-auth-core==3.1.0
stripe==1.37.0
urllib3==1.24.1
whitenoise==3.2.1
psycopg2==2.7.7
psycopg2-binary==2.7.7
Did you properly configured template dir inside your settings
Yes. The url works fine on Localhost cause I made changes in django/contrib/auth/views.py in site_packages
but as i am trying to deploy to heroku, it shows template error here only
Can you show your template settings
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
],
},
},
]
--> epiktaskerapp
--> templates ```
code structure is like this
Oh
I just imagined that you would use the templates folder django-admin created for you
That may be your problem and I'm not sure how can your local one work
Mind trying to either relocate the templates to the root directory
Or simply change the 'templates' to 'templates/epiktaskerapp'
Although
I think APP_DIRS is for searching inside the apps for the templates
hmm
Consider me a beginner.
I am trying changing templates
And my localhost worked
cause I changed (django/contrib/auth/views.py in site_packages)
"""
Display the login form and handle the login action.
"""
form_class = AuthenticationForm
authentication_form = None
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'restaurant/sign_in.html'
redirect_authenticated_user = False
extra_context = None
template name here from registration/login.html to restaurant/sign_in.html
Why did you change that?
You should NOT change any library code like that especially if you are a beginner
You should instead inherit the class in this case and put your template there
I changed because I was following a tutorial with django 1.10 and he has restaurant in url
And I wanted the same in url in django 2.1.7
If the tutorial changes library code stop that tutorial immediately
Inherit LoginView instead
And in the class that you inherit the LoginView change template_name
That's it
Naa tutorial didnt change library code cause in old version I guess it wasnt necessary?! (maybe)
Okay! I will make it as it was on default. I will update you in few minutes
Anyone knows anything like whitenoise but for media?
What do you mean?
Sorry
Whitenoise is a wsgi-library for serving statics with the wsgi application
Instead of serving them with another server
Nothing? :(
i have a very small project that takes information from files and stores it in a .js file for display in a browser
it needs to update pretty often
what is a good way to structure/run this project?
Anyone have best practice in dealing with abstract views in Django?
for example
class NoteAddView(LoginRequiredMixin, SubscriptionRequiredMixin, AjaxMixin, CreateView):
template_name = 'rental/standard_form.html'
form_class = NoteForm
def get_success_url(self):
return self.request.META.get('HTTP_REFERER', '/')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['page_title'] = 'Add Note'
return context
class ContactNoteAddView(NoteAddView):
model = ContactNote
def form_valid(self, form):
form.instance.contact = Contact.objects.filter(pk=self.kwargs['pk']).get()
return supe r().form_valid(form)
I'm thinking this is the cleanest way to doing it but im feeling a bit unsure
if anyone has any other suggestions
Are you going to be using NoteAddView elsewhere @full lynx ?
Yes, for each model more or lesss
Have like a dozen xNoteAddView(NoteAddView)
@tardy pasture
Without looking at things more in-depth, nothing you wrote gives me code-smell feelings.
@full lynx
maybe that space in supe r
but that's really just linting / typos.
I ended up going with the above syntax yesterday and my subsequent children models look like
class LeaseNoteAddView(NoteAddView):
model = LeaseNote
form_class = LeaseNoteForm
def form_valid(self, form):
form.instance.lease = Lease.objects.filter(pk=self.kwargs['pk']).get()
return super().form_valid(form)
class LeaseNoteEditView(NoteEditView):
model = LeaseNote
form_class = LeaseNoteForm
class LeaseNoteDeleteView(NoteDeleteView):
model = LeaseNote
it looked tidy enough
Do more of the inherited views have things like custom validation?
There's a couple of things that I would consider:
If it starts to feel boilerplate-y, then there's probably an optimization that you can make with the views. If you have a bunch of views where all you are doing is specifying models or form classes, you might be able to get away with a single view.
As a counterpoint, you might be over-optimizing; this is a pretty valid use of abstract views, and it gets the job done.
Traceback (most recent call last):
File "/home/sm/PycharmProjects/messis-restful-api/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/sm/PycharmProjects/messis-restful-api/venv/lib/python3.6/site-packages/flask/cli.py", line 76, in find_best_app
app = call_factory(script_info, app_factory)
File "/home/sm/PycharmProjects/messis-restful-api/venv/lib/python3.6/site-packages/flask/cli.py", line 114, in call_factory
return app_factory(script_info)
File "/home/sm/PycharmProjects/messis-restful-api/app/api/__init__.py", line 17, in create_app
app.config.from_object(config_by_name[config_name])
KeyError: <flask.cli.ScriptInfo object at 0x7f8a7758fa20>
What am I doing wrong when trying to execute that with IntelliJ PyCharm, with the run configuration thingy?
Is it possible to translate JsonResponse in django
with iI8n
Can you run Flask offline?
sure, it'll happily run off the users localhost.
Ok thanks
Im getting a weird issue where the autofill for Google places API sometimes doesn't work. Im using Flask for my app. Has anyone else had this issue? Usually refreshing the page fixes it, but its really annoying and I don't want users to try it till its 100% working
Never had the problem using it before on just pure bootstrap projects until now
I'm getting a 404 error on my flask app. I'm using this line of code to get information from the html.
@app.route('/p1') def search(): N = request.args.get('name') #name print(name) N = request.args.get('gender') #gender print(gender) return render_template('name.html', gend=gender) #no extra comment at end.
My html:
`<html>
<style>
h1 {
font-family: monospace;
color: blue;
}
p {
font-family: monospace;
color: blue;
}
p {
font-family: monospace;
color: blue;
}
</style>
<title>Form input test</title>
<h1>Form Input test</h1>
<form name="/p1" action="/search" method="get">
Name: <input type="text" name="name">
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input type="submit" value="Submit">
</form>
<p>Testing testing, 123.</p>
</html>
`
(Im using flask)
Okay I'll be back later. Tag me please.
for anyone who's familiar with pythonanywhere web apps... are source files private/secure?
I want to make a reddit bot callable on a webpage (it updates user flair for our subreddit and the bot goes down sometimes and they message the mods to complain then)
but the config file has login credentials/keys etc
django
how can i get just the request headers and not all the other crap i get with requests.META??
@uneven jasper if you are getting form in you gotta add in methods=['GET','POST'] within your route
ie @app.route('/p1', methods=['GET','POST'])
How can you run flask on a particular domain?
Wherever you host it you can configure the domain DNS to point to it
ie I use Heroku and when you add a custom domain it just gives you a string to point the url to
So I went thru the examples on deploying with heroku but im still confused on how to deploy using a certain url
@limber orchid I believe they are. Yet, you'd be better checking this out with their support. They are really nice.
yeah I finally heard back from them just now, they said as long as it's not in a static directory or being served to the user somewhere in the code, then it can't be seen
thanks!
@rough jasper I think you can filter by those with keys starting with HTTP_.
@native tide Domain and url are different things. Can you show an example of what are you trying to achieve?
basically what I want is instead of http://127.0.0.1:5000/solve I want it like http://dominus/solve
Is that for local usage only?
Or do you want it to be available to everyone in the internet?
everyone on my wifi network
That might not be easy. In that case you will need some kind of local DNS setup or make everyone adjust their hosts file and add record pointing to your IP address there.
I can get the hosts file edited
Everyone who is intended to be able to access the resource will have to do it.
Not just you.
In that case it's doable.
First you will need a static IP address.
I.e. DHCP won't work.
Can it be a vps server I rent?
As long as it's reachable via the static IP address - yes, sure.
Next xxx.xxx.xxx.xxx dominus line should be added into the hosts file for every client accessing the server, where xxx... is the IP address.
Start with yourself and see if it works.
Ok
Actually, IP address should be first. I've edited the message.
Obviously, you will have to set up your resource on that VPS you mentioned on port 80.
@candid basalt but referer doesn't start with HTTP_
Wait why port 80?
So basically edit my hosts file to xxx.xxx.xxx.xxx dominus and then start the flask server on that vps using localhost:80
http://dominus/solve has no port specified. This means default one is used. Default port for HTTP is 80.
Ahh ok
Yes, you pretty much nailed it.
@rough jasper is it not? https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.META
no that gives me all the crap i don't want
@candid basalt
A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:
the available headers depend on the client and server
and i don't care about the servers headers
Did you try to filter by HTTP_?
REMOTE_ADDR doesn't start with HTTP_
i wan't to recreate http://azenv.net/
but local
within django
i am probably being stupid but it is kinda late
I think REMOTE_ADDR is not a HTTP header.
oh shit
At least I'm not sure if it has to deal with the protocol itself.
you're right
In any case if you want a given list of headers - you can just pick those you are interested in and output them.
i am stupid
i need to filter for HTTP_
and the otherones i have to just use the key itself
thnx for your help @candid basalt
@candid basalt Hey again. So I set my macs localhost file to xxx.44.xx.238 dominus. I then logged onto the vps with xxx.44.xx.238 as its IP and setup my flask application on it
I opened up http://127.0.0.1/solve
on my vps and it loaded fine. I then tried to go to
http://dominus/solve but all I got was the little loop
that signifies that it is loading
this has happened for about 10 minutes now. Any reason as to why?
Maybe look at the logs
nothing on the logs
Yup it just keeps going and then gives me the "took too long to respond"
Found this question on SO
I'm trying to run a flask server on my desktop PC that is publicly available on the internet. I've done the following:
Set up a static IP address: 192.168.1.11 (http://i.imgur.com/Z9GEBYV.png)
no solution though
Hello! I need some advice setting up a flask+uwsgi app
Been trying for more than 12h in a row! any experts around?
@everyone ?
hello
is there a way to return an image and json data in one response ?
using flask
I have a really basic html/php form system. The user can submit their name, and message. To prevent spam I want to add a "cooldown" like feature that disables the user from continually entering bs into my form. How would I go about doing this?
use ip or session or cookie
In your database or redis or whatever $_SERVER["REMOTE_ADDR"] save this and the creation time with the name-message
When the user sends another post request, check if the remote address is been used before, if yes check if it is still on cooldown( something like current_time - last_entry.time > cooldown: allow)
If not uhhh
return 429 or smt
This is just how would you do with ip I guess
You can use session or cookies but they are rather easier to create a workaround
@native tide I did not work with flask all that much, but it may depend on the command you use to run it with. It should accept connections from the public interface, not from 127.0.0.1
@maiden valley Don't ask to ask, just ask your question. =]
@jovial vapor It depends. You can try to return base64-encoded image as a part of your json response.
@native tide depends on the setup. You can save the time and date of the last message by username and check it for every new submit if it's recent or not.
@candid basalt Thanks! :]
So, I am trying to configure Flask + uWSGI + NGINX, and I used to be agle to route the app folder with @app.route('/'), and access it with www.example.com/myapp
but now it only works if I route it like this: @app.route('/'myapp/)
I tried a hundred thousand configurations for ini file and nginx 'sites-enabled/default'
including mounting the app with
manage-script-name = true
mount=/myapp=myapp:app
in the ini file, without success!
with previous apps I was using the "ugly hack" SCRIPT NAME = /myapp and uwsgi_modifier1 30; in the nginx default file
the only thing that differ from the methods is that I was using python 2 before, and now python 3, and I found this thread:
Any thoughts?
I also followed this: http://flask.pocoo.org/docs/1.0/deploying/uwsgi/
Solved it guys, I had a stupid backup ini file that was overriding the changes on the one I was modifying, thank you anyways!
Should I ignore this
[DOM] Input elements should have autocomplete attributes (suggested: "current-password"): (More info: https://goo.gl/9p2vKq) <input type="password" name="password" required id="id_password">
It would be better to implement it.
But it's django form
thing
Admin site
I am trying to find bugs / glitches / weaknesses
Django's PasswordField doesn't add this automatically?
It's not an error, it's a suggestion by chrome to improve the page.
No
This is just something that makes it easier for people to use the password form
Unless you modified the django admin forms I wouldn't worry about those.
I haven't
Hey guys anyone here well versed in domain name zone dns configuration?
Or knowledgeable?
@candid basalt i ended up running it on heroku and it opened it for everyone
What's the best way to make an <img> zoomable and draggable? Tried "wheelzoom" and some other google results but didn't really work.
Basically I have a large image of a graph that I want to be able to follow by dragging on the image with the mouse as well as zooming in and out on it.
2 things
- Lets say I run a Flask server on Heroku. Is it possible that when I go to a specific url (on the flask/heroku server so like http://[my app name here].herokuapp.com/solve) it opens another tab on my browser?
browser as in the browser I used to go to the http://[my app name here].herokuapp.com/solve
- How can I set a custom domain for my heroku app? So I want the url instead of
http://[my app name here].herokuapp.com/solveit goes tohttp://dominus.com/solve. Is it modifying the host file?
@native tide
- Opens new tab when you visit the url by copypasting it into the browser address bar? Probably no.
- For services like heroku hosts approach may or may not work depending on how they handle incoming requests. There are routers involved, so it will probably not work without bought domain you own.
- Naa like using the webbrowser module. So I guess i go to http://[my app name here].herokuapp.com/solve and it does a redirect to another url
- So I have to get my own domain. Then what?
@candid basalt
With 1) I'm still not sure I follow.
With 2) Heroku docs should have info how to do it. I did not work with Heroku all that much.
Ahh ok
So basically lets say I go to http://127.0.0.1/get
How can I then go to https://twitter.com/ for exmaple
Nevermind I got it to work
How I redirect the user to another flask page with on_click in html?
Can't I use url_for?
To provide an url into the JS function - yes.
To do a redirect without JS - probably not.
How can I format the return content on flask?
i want to learn web dev with py. djange or flask? which one is better?
guys, do you have any idea why test_text_content passes in this test case
from django.test import TestCase
from django.urls import reverse
from .models import Post
class PostModelTest(TestCase):
def setUp(self):
Post.objects.create(text='just a test')
def test_text_content(self):
post = Post.objects.get(id=1)
expected_object_name = f'{post.text}'
self.assertEqual(expected_object_name, 'just a test')
but if I add another test case, where I create another object in the same model Post, the first test case fails?
this is the second test case:
class HomePageViewTest(TestCase):
def setUp(self):
Post.objects.create(text='just another test')
def test_view_url_exists_at_proper_location(self):
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
def test_view_url_by_name(self):
resp = self.client.get(reverse('home'))
self.assertEqual(resp.status_code, 200)
def test_view_uses_correct_template(self):
resp = self.client.get(reverse('home'))
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed(resp, 'home.html')
I'm following tutorial from Django for Beginners book
this is the result ```
E
ERROR: test_text_content (pages.tests.PostModelTest)
Traceback (most recent call last):
File "/home/standa/PycharmProjects/rango_project/pages/tests.py", line 13, in test_text_content
post = Post.objects.get(id=1)
File "/home/standa/PycharmProjects/rango_project/venv372/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/standa/PycharmProjects/rango_project/venv372/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
pages.models.Post.DoesNotExist: Post matching query does not exist.
Ran 7 tests in 0.084s
FAILED (errors=1)```
I'm trying to deploy a django website on a LAN network/intranet sort of thing. Right now the only way to access the site is through this address: 192.XXX.XX.XXX:8000, but I want others on the same network to be able to access it through putting 'intranet/' in a web browser, is it possible to redirect it?
Just ask your question @steel flicker
There are, but they may or may not be online and they're not going to reply unless they know what you're asking
@hallow ferry That sounds like a networking issue. You need to configure the client's DNS to resolve "intranet" to "192...".
So I'm trying to make an API with a database I have
I'm not really sure how should I structure the endpoints, though
let's say I have a list of users. As far as I understand, the endpoint /user should return the full list of users, while /user/user_id should return a specific user
however, what happens if the user list is really big? Wouldn't that make it too slow?
make it with pages
With filters
/user?sex=male&age=24&is_god=False&page_item_count=12&page=10
@dusk light , as @lost saddle mentioned, use pagination when you query and add it into the URL as a parameter. I'd suggest paginating on the database level instead of the client side javascript
In a database
So I could just store it in a variables like this? :
gender = "Male"
name = "Jeff"
You lost me. I don't understand what you are trying to do
REEEEEEEEEEEEEEEEEEEdis
Ok, sorry. Let me clarify some things.
I'm just trying to get information from a survey that I make and store it (I don't care how, I only need the data until the user gets the results.) Then use that data from the survey to pick a product from amazon and give them the link.
When does the user get the result
How does the user get the result
Where does the user get the result from
?
The user gets the result at the end of the survey.
They get a amazon referral link
They get the result from us, after our system decides what they should get based off survey informatin.
I'm just asking how I should store the data.
You don't store any data
You get it from the form
You put it inside your get_result_from_user_data function
And return the result
There is no storing involved
Everything happens in a view
Okay
Still though, any parameter like that would be optional for querying, so someone who doesn't specify any parameter like that would still have to deal with waiting
?
just as a comparison in the API I've made (which is just a flask-restplus hello world with a few modifications so it queries my database), querying a specific user takes about 20ms, while taking the whole user list takes 5 seconds
I understand that I can use parameters so queries can only get what they need, but my issue is what should I offer in the endpoint by default
Oh, wait
I misunderstood what you told me about pagination
apologies
Does anybody know how i can access the equivalent of app.env in a Flask Blueprint?
Of course, asking for help = immediately finding a solution
If anyone else has this issue, import current_app from flask, and use that as a reference to your primary app, that will have the env variable
I want to create image gallery like this. The rows are always equal and dont leave empty spots. I got it working, but the problem id that, I use django and the images gets uploaded with django, and the classes stay always the same, second problem was that the images stays always on the same row.
<div class='pics_in_a_row'>
<div class='img1'>
<img src='img1.png'>
</div>
<div class='img2'>
<img src='img1.jpg'>
</div>
<div class='img3'>
<img src='img3.jpg'>
</div>
</div>```
```CSS
img {
width: 100%;
height: auto;
vertical-align: middle;
}
.pics_in_a_row {
display: flex;
}
.img1 { flex: 1.3344; }
.img2 { flex: 1.3345; }
.img3 { flex: 0.7505; }
.img4 { flex: 1.5023; }
.img5 { flex: 0.75; }
.pics_in_a_row {
margin: 25px 0;
}
.pics_in_a_row > div:not(:last-child) {
margin-right: 2%;
}```
THIS IS CREATED BY Pat McKenna.
So I need Javascript code or something to put the right flex class for the image, order to fit to the line.
For some reason this
`
<h1>Click 'Continue' to get started.</h1>
<a href=”/form1”><input type=”button” value=”part1”></a>
Is showing this
And when I click the textbox it gives me a 404 error.
This is main.py
`from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
import jinja2
app = Flask(name)
@app.route('/')
def home():
return render_template('index.html')
#survey part 1
@app.route('/form1', methods=['GET','POST'])
def part1():
return render_template('part1.html')#required, otherwise it would render part2
name = request.args.get('name') #name
print(name)
gender = request.args.get('gender') #gender
print(gender)
return render_template('part2.html', gender=gender, name=name) #no extra comment at end.
#survey part 2 -- GENERAL hobbies and intrests. See project overview.
@app.route('/form2', methods=["GET","POST"])
def part2():
genhobby1 = request.args.get('hobbieslist1')
print(genhobby1)
genhobby2 = request.args.get('hobbieslist2')
print(genhobby2)
return render_template('part3.html')
if name == "main":
app.secret_key = 'super secret key'
app.debug = True
app.run()
#1 queston per page
#Dynamic questions
`
make sure you're using the correct characters for your quotation marks in your html. it looks like you're using ” instead of "
Hello. Is this the right place to ask about using Beautiful Soup?
@rocky wyvern just ask
For anyone trying to make a REST api with Flask, here is a really useful tutorial: http://polyglot.ninja/rest-api-best-practices-python-flask-tutorial/
Total noob: How do I call a function only after a specific event (uploading data) has been performed?
In Flask
make a request to a backend Flask URL with the function using JavaScript
Could you give an example?
@cursive cairn , what kind of action are you attempting to perform? Is it a clientside UI interaction or a serverside processing action?
@fathom prism Render some graphs upon uploading some data
@cursive cairn , is the user "uploading" data via a POST request to your web server and getting a HTML page or JSON response back?
Uploading via POST. I want to upload data and render the graphs on the same page, directly after data has been uploaded
@cursive cairn, what framework are you using?
- User uploads to your endpoint /POST (e.g. /upload)
- <Do stuff to your file> (save to database, parse, etc)
- Return a JSON payload via ajax
- Have your javascript perform some sort of graph rendering
Flask, Flask-Upload. Plotly.js for graphing.
The example on the flask upload doc is the exact one you could follow
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
rec = Photo(filename=filename, user=g.user.id)
rec.store()
flash("Photo saved.")
return redirect(url_for('show', id=rec.id))
return render_template('upload.html')
https://pythonhosted.org/Flask-Uploads/
Replace the returns with a jsonify(your response)
To render the graphs on the same page would I just redirect to the same page, but with new information?
No redirecting of pages needed. Your javascript would make an AJAX call to the /upload URL
Oh wow. I didn't even know AJAX existed. Learn something new everyday. Thanks! 😃
Np, best of luck on your journey
Thanks!
Do you have any resources you'd recommend on learning to build webpages, specifically on Flask?
The common one that the community usually promotes is Miguel's https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
Wow! Thanks so much!
x = document.getElementsByClassName("img1");
$("img").each(function() {
height = this.naturalHeight;
width = this.naturalWidth;
ar = (width / height);
console.log(height + " x " + width + " = " + ar * 2);
var element = document.getElementsByClassName("img1");
for (var i = 2; i < element.length; i++) {
var element = document.getElementsByClassName("img1");
for (var i = 0; i < element.length; i++) {
element[i].style.flex = ar * 2;
};
};
});```
So What I am trying to do, is get every images height and width. Then divide it (width / height) and put that in the div what is .img1
Example: Html <div class="img1"> <img src="butterfly.jpg"> </div> <div class="img1"> <img src="butterfly.jpg"> </div> <div class="img1"> <img src="butterfly.jpg"> </div> <div class="img1"> <img src="butterfly.jpg"> </div>
So put that image width divided by height to img1 div as a flex.
Output: <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div> <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div> <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div> <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div>
so the problem is:
It prints out the last third images height / width.
Hello, I'm currently trying to learn to use Flask and I'm trying to do so following best practices.
I am currently trying to add a bootstrap navbar and I want to give the template a list of links to add to the navbar. I want this navbar to appear on all pages of the site, but I'm not sure how to go about doing that.
From what I can tell I could create a list called navLinks or something and pass it as a parameter to the render template function, but I want it to be global & it seems like bad practice to add it to every call of the render template because the context that you pass should be specific to the page being rendered.
I have been working from this tutorial, http://flask.pocoo.org/docs/1.0/tutorial/, and I'm currently modifying things to use bootstrap and get a better understanding of how Flask works.
Are you using templates for your html? In that case you can create a base template that will always contain the navbar, which all pages include.
make your main page as template.html
then your other pages can reference that using
using the Jinja templating language http://jinja.pocoo.org/docs/2.10/
Pretty sure flask ships with it.
https://www.youtube.com/watch?v=QnDWIZuWYW0&index=3&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&t=0s explains it i think.
In this Python Flask Tutorial, we will be learning how to use templates. Templates allow us to reuse sections of code over multiple routes and are great for ...
@sleek tartan
Yes I am using templates
I have a base template that contains the following include
<header>
{% include 'base/navbar.html' %}
</header>
My navbar.html contains
<nav class="navbar navbar-expand-sm bg-dark navbar-dark sticky-top">
<a class="navbar-brand" href="#">
<img src="{{ url_for('static', filename='Images/nav_icon.png') }}"width="30" height="30" class="d-inline-block align-top" alt="">
Baker Codes
</a>
<ul class="navbar-nav">
{% for link in navLinks %}
<li class="nav-item">
<a class="nav-link" href="{{ link[1] }}">{{ link[0] }}</a>
</li>
{% endfor %}
</ul>
</nav>
This currently works for the index page, but not any others.
Whats wrong with my quotation marks...?
In python the quotation marks make a string green. In html they're not. I'm using atom.
Doesn't mean something is wrong. They're different languages so Atom uses different syntax highlighting rules for them
Though the quotes for button look wrong
You should use the "straight" quotation marks instead of these ”
I kind of figured out my issue.
In my init file I used a context processor
@app.context_processor
def inject_navList():
navLinks = {'links' : [{'name' : 'Home', 'url' : url_for('index')}, {'name' : 'Hello World', 'url' : url_for('hello')}]}
return dict(navLinks=navLinks)
That allowed me to access the dictionary without passing it to the render template function.
Anyone more familiar with flask know any best practices for where to declare context_processors?
@terse portal this is a Python web development chat
Hello,
I like to create a website with flashcards, but I don't have idea how to create a models with it.
Do you think that such a thing makes sense?
from django.db import models
class FirstFlashcard(models.Model):
LANGUAGE_CHOICE = {
('PL', 'Polish'),
('EN', 'English'),
}
first_language_choice = models.CharField(max_length = 10, choices = LANGUAGE)
flashcard_text = models.CharField(max_length = 50)
class Meta:
verbose_name_plural = 'First Flashcard'
def __str__(self):
return self.flashcard_text
class SecondFlashCard(models.Model):
LANGUAGE_CHOICE = {
('PL', 'Polish'),
('EN', 'English'),
}
second_language_choice = models.CharField(max_length=10, choices = LANGUAGE_CHOICE )
first_language_text = models.ForeignKey(FirstFlashcard, on_delete=models.CASCADE)
second_flashcard_text = models.CharField(max_length = 50)
class Meta:
verbose_name_plural = 'Second Flashcard'
def __str__(self):
return self.second_flashcard_text
Why do you have two separate models? One for each side of the flash card?
@proper hinge I wanted to create one model, but I do not know how to make choice_field also contain the possibility of entering text (specific text to a specific language).
@proper hinge at the moment this is only a concept and I would like to come up with the most reasonable idea
I'm not familiar with Django forms honestly
But just from the perspective of model design having two models seems redundant
@proper hinge I think you have right. In that case, I must think how to implement it in one model in a logical way, right way.
Some ideas:
- In one model, make text fields for the front and back sides as well as language fields.
- Have one model with a single text and language field, then create a new model which "pairs up" two flashcard models using foreign keys.
Building on the first idea, instead of two language fields, you can have one that is like PL_EN or EN_PL so you can deduce the language of each side from a single field.
Though that doesn't work too well if you plan on having more than just those two languages
It's easier to add support for more languages when fields are separate
@proper hinge At the moment I focus only on two languages, but probably in the future I would like to add more
@proper hinge I will try to implement it in some way and share the result. Thank You for advice!
You're welcome
Why not have just one flashcard model without language select and just have il8n
>>> e.aggregate(p=Count(F('likes')))
{'p': 51}
>>> e.aggregate(p=Count(F('dislikes')))
{'p': 21}
>>> e.aggregate(p=Count(F('likes'))-Count(F('dislikes')))
{'p': 0}
🤔
>>> e.aggregate(p=Count(F('likes')))
{'p': 51}
>>> e.aggregate(p=Count(F('dislikes')))
{'p': 21}
>>> e.aggregate(p=Count(F('likes')-F('dislikes')))
{'p': 1071}
>>> e.aggregate(p=Count(F('likes'))-Count(F('dislikes')))
{'p': 0}
>>>
I'm lost
@uneven jasper you shoud use {{ url_for(function_name) }} instead of /function_name
btw you cannot use multiple return statements at same indentation
basics of python
btw you cannot use multiple return statements at same indentation
import random
def f():
if random.randint(0,1):
return 0 # 8 space
else:
return 1 # 8 space```
So I'm making a backend using flask and hosting it using heroku
the idea is that a user submits certain keywords to the program
when that keyword matches text found somewhere in a external file
that is hosted in the backend
it needs to alert the user
So i know what i wanna do
basically im confused on
how flask is going to manage the users seperately
so like if user 1 has keyword "ok" and user 2 has keyword "bye"
and if the program finds the work "bye" in the external file
how will it only return the alert to that user
Hey guys, i wanna make a form that can edit multiple instances of some object with different values with 1 click
each row is different instance, i want to put values in 'stan' collumns and just click blue button to save values to objects
is that possible and if yes then how?
i tought that Formsets are solution but from what i understand it is when you want to provide single value to multiple objects is that right?
oh i frogot to mention that I'm using Django
Hey,
So... I'm working with Flask...
I was wondering on how you could do a custom form kind of thing, if that makes sense. I don't know how to explain it.
So like the user can write text, then add an image in-between, add code maybe, then continue writing. Like how they do it on Medium and on other blog sites. Something like what's in the image below.
If i use django i won't be able to have asynchronous code right? So doing transactions with the database would make the website slower since it needs to finish the task before it continues running the code.
How could I avoid that? any suggestion would be appreciated
sry for my lack of experience if I said something wrong
i briefly looked into this it sounds like people are using celery
Does anyone know why using MySQL while hosting locally on windows would be a problem?
do you really have to go through two weeks of "app review" to post to a fb group?
Hi all. How does everyone work with testing out their models in Django? Looking to learn about some more complicated things sub queries etc. Whats your work flow? Django shell?
Hey guys
Anyone here had experience with lamdba with python..mainly authentication.
Are there stuff like expessjs in python?
Hey all with Django annotations, if I wanted to do a calculation later, is it something like this? Right now win_rate returns just 0 in my f-string as {win_rate:.2}
https://django-allauth.readthedocs.io/en/latest/templates.html
The all auth docs say to override the account/login.html create a file with this name and it should work
is it saying to create a module called account then add a login.html?
ty
When using flask, is there a wrapper that can be used for when a session is destroyed?
I'm looking for a way to clear temporary files after a user leaves
looks like there are a couple of options, but its limited because session expiration seems to be handled by the db backend
a) delete them when the user logs out/some other manual trigger
b) occasionally check which users have not done anything for a while and clean them up
c) figure out if the db backend you use has a hook for it
There isn't a db backend, it's all going to be working with image files
However, I think I've found a workaround that should do just fine, I'll just need to do some restructuring
Essentially, what I was thinking was, front end / smaller web app I'm working on now (partially for a class) would AJAX files at this backend, which would save them, allow the users to pick a function on a different backend (one that I've already made), and then ajax to my backend which would call the other backend and then save that response and give the frontend a url to display that.
I've narrowed it down to the user will pick a function and upload the image in one go, allowing me to save it for as long as it takes to make the response, then wipe it (or just keep it in a temporary file object), and then save the new one and have the front end make a request when it's loaded and delete it serverside.
It's terribly thought out, but the deadline isn't for another few months and I'm already making pretty strong headway into this
yeah i would just not tie the activity to the session directly. decouple it and just let the session access the status and results of the activity.
if you find out the user wont come back to download the file you can delete it, but otherwise just let your system process it and the user check any status/results by loosely associating their session with the activity [eg via an id]
this way you can just say 'all files created will be deleted within 1 hour' and if the user downloads it or not you still know its time to delete it
Yeah that might be another good approach
I've never really dealt with file uploading or temporary files, so this is good practice
Hey folks, I am trying to learn web scraping and looking for more tutorials to do. Do you have any favorites you suggest I try?
Anyone using aws S3 with flask and boto3? I am trying to set the output size before upload using PIL but its not working. Is there a special command anyone knows that will work?
I have a stupid question, Should i check for password confirmation in the frontend or the backend ?
I mean which is the best ?
What are you handling it with?
ie flask or Django? I use flask, and these modules will do most of the work for you.
from flask_login import login_user, current_user, logout_user, login_required
and the PW hashing
from werkzeug.security import generate_password_hash,check_password_hash
I use django rest framework
I hashed the password , by confirm i meant 2 input fields named password and confirm password
I just asked which is the best practice to do it, in the front end (react native app) or the backend (django api server)
Ah ok. I just do it on the frontend, and if its valid it commits the hash to DB:
email = StringField('Email', validators=[DataRequired(),Email()])
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired(), EqualTo('pass_confirm', message='Passwords Must Match!')])
pass_confirm = PasswordField('Confirm password', validators=[DataRequired()])
submit = SubmitField('Register!')```
im trying to override the allauth default template. The docs say For instance, the view corresponding to the account_login URL uses the template account/login.html. If you create a file with this name in your code layout, it can override the one shipped with allauth. Is this saying i create a module called account and a template in it called login?
How would I use the redirect function to redirect to my / page in Flask
I've tried
redirect(url_for('/'))
Oh just redirect('/') will work
Look into Flask/Django
Hey what do you think to use django with react for the frontend ?
django and react is a good stack to work with
Oh okay cool, thx @sturdy sapphire
I'm looking for some advice on the "djangonic" way of dealing with apps
what size functionality "should" be contained in one app; and what functionality should be split up
also, in a completely different direction, what framework is most commonly used to unit-test django http requests
Has anyone got a way to handle keybbards on android and IOS effecting the website layout, making forms move wayy up
hey i want to make a simple website with flask with basic things like info pages/blog posts and somewhere to upload files, where should i go to learn this stuff?
@quaint ledge virtually any Flask tutorial, just google this and pick any
ok
How do I serve a file from flask to my home server? I want to be able to send a get request with a fpath and download the file. Is it possible? Will only run in my local network
ul {
width: 100%;
background: transparent no-repeat fixed 0% 100%;
}
<ul>
<li><a class="active" href="RpmhdpSettingUp.html">Challenge 1</a></li>
<li><a href="RpmhdpHNavbarBio.html">Challenge 2</a></li>
<li><a href="RpmhdpColumns.html">Challenge 3</a></li>
<li><a href="RpmhdpTables.html">Challenge 4</a></li>
<li><a href="RpmhdpEditor.html">Challenge 6</a></li>
<li><a href="Rpmhdp7.html">Home</a></li>
</ul>
Anyone know why the CSS is not applying the ul?
This works but i'm not sure if it is the best way to do it, Any suggestions ?
btw using django rest framework
@native tide Aside from your indentation, everything looks good. Depending on what you are inheriting from, you may not need those arguments to super.
Does anyone have tips on how to reverse engineer an WebSockets based game? Is wireshark the way to go or nah? Firefox doesn't let you see what's being sent over the WS connection, does anyone know if chrome does?
@vagrant adder I tried that and it gave me this error: jinja2.exceptions.UndefinedError jinja2.exceptions.UndefinedError: 'form1' is undefined
This is my code:
`from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
import jinja2
app = Flask(name)
@app.route('/')
def home():
return render_template('index.html')
#survey part 1
@app.route('/form1', methods=['GET','POST'])
def part1():
return render_template('part1.html')#required, otherwise it would render part2
name = request.args.get('name') #name
print(name)
gender = request.args.get('gender') #gender
print(gender)
return render_template('part2.html', gender=gender, name=name) #no extra comment at end.
#survey part 2 -- GENERAL hobbies and intrests. See project overview.
@app.route('/form2', methods=["GET","POST"])
def part2():
genhobby1 = request.args.get('hobbieslist1')
print(genhobby1)
genhobby2 = request.args.get('hobbieslist2')
print(genhobby2)
return render_template('part3.html')
if name == "main":
app.secret_key = 'super secret key'
app.debug = True
app.run()
#1 queston per page
#Dynamic questions
`
This is index.html
`<h1>Click Continue to get started.</h1>
<a href='{{ url_for(/form1) }}'><input type="button"></a>
`
When function hits the first return, funtion ends
Take a look at python basics
Also
{{ url_for('part1') }}
Okay thank you.
Complete web noob here. I'm trying to get keystrokes on a webpage to python as the keys are pressed, I can see the request on each keystroke, but info print is always b''
<!doctype html>
<title>Testing</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).keypress(function(e) {
$.ajax({
method: 'POST',
url: {{ url_for('keypress') | tojson }},
data: e.which
})
});
</script>
import flask
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('base.html')
@app.route("/keypress", methods=["POST"])
def keypress():
app.logger.info(flask.request.get_data())
return flask.jsonify(result="TODO")
if __name__ == "__main__":
app.run(debug=True)
any pointers in the right direction would be appreciated 😛
figured it out, e.which to e.key in the javascript
follow up question.... how do I debug javascript
oh neat, I did not know that!
Are there any guides you guys recommend for learning HTML/CSS?
Can someone help me clear my confusion? I am trying to render graphs on a page after the user uploads data. I have a bunch of functions in Python that make the json needed for rendering the graphs using a Javascript library. What would be the most efficient way to pass uploaded data to my python functions and then the JSON back to Javascript without reloading the page? I assume I'll have to use AJAX?
@cursive cairn if you do not want to reload yeah you have to use AJAX (or Websockets or stuff like that, but will be overkill).
You are probably better off simply reloading the page, that is not so bad tbh
How do I send data from AJAX to Flask, run some functions, and then pass the data back without reloading?
@cursive cairn create a Flask view that receive data (from a form or JSON for instance) and returns new data
And send a request to this view from within the page, using AJAX for instance
yeah im refreshing the page
I'm making a progress bar..
is there anyway I can make it look cooler
publish.css("""
.pwnr-progressbar {
border: 3px solid #bbbbbb;
border-radius: 10px;
height : 30px;
background:#cccccc;
overflow:hidden;
display:inline-block;
}
.pwnr-progressbar-inner {
height : 24px;
padding:3px;
padding-left:5px;
font-size:17px;
color:#005500;
position:relative;
background:#77ddee;
}
.pwnr-progressbar-eta {
margin-left:3px;
display:inline-block;
position:relative;
top:-10px;
}
""")
how do i put my flask app online?
what
yea i know that
im asking how to put it on a domain
like www.foobar.com
yeah...
im being told to use AWS but not sure how
also heard heroku but also heard its not good
Is there a easy spinup for django? Like generic setup
Ive worked with php etc (drupal) for.. last decade.. Django sounds nice
I know this is silly, but I am trying to learn js, but I am a tad confused. So I made a json file that contains jokes, and I would just like to simply "lists " them on a site, like I want the question and answer to just show up in the center of the screen, and after a wait time, then show the next joke. Any idea how I can do this?
also these are the jokes
I just took them from the programming dad jokes github page, and turned them into a json file
nvm I think I figured it out
Nope
so does anyone know the best way to show two values, have a wait time, then show the next two in the json?
the wait time is not issue, its the showing the values
how do i send POST data without a form
@quaint ledge http://flask.pocoo.org/docs/1.0/deploying/#deployment
the django docs say
allauth ships many templates, viewable in the allauth/templates directory.
For instance, the view corresponding to the account_login URL uses the template account/login.html. If you create a file with this name in your code layout, it can override the one shipped with allauth.
so to override the all auth html do i create a module called account and a file called login .htm
I'm a tad confused about backend web dev languages. How does a non OOP language like Python or JS work with back end stuff? Like I guess I'm just not seeing the capabilities of a scripting language besides making little kiddie scripts
yeah nvm I'm an idiot
@teal scroll which self deployment option is the best? the descriptions arent that helpful
what do cloud services mean when they say "instances"?
most likely a virtual machine
@untold zealot haha kiddie scripts, really? tell that to instagram, youtube, the entire machine learning and data science industries, the entire visual effects industry, many other things, etc. like any language there are areas in which it excels and areas in which it does poorly than others. and also like anything else, it's also dependent on the skill level of its user
@quaint ledge yes "instance" refers to a single virtual server of some sort. regarding deployment -- which is the "best" depends on your needs. do you already use aws or heroku or any of those? is there a budget for this project? do you want something that's easier to work with or more painful but cheaper? etc
oh ok
@quaint ledge oh sorry, you said self-deployment. okay that's different, one can safely say that gunicorn + nginx is key
i would not bother with those other choices
i decided to go with a virtual server
digital ocean
it seems good
seems cheap too
except that i am a huge fan of Caddy as a web server that is dead simple to use and performs about 80% as well as nginx and so yeah
DO is fine
is this for fun or work or intended to be running in production with users and whatnot soon
its for fun
DO is fine, the obvious downside with any vps provider is that you now have to run the vps and all the crap on it
which is why i love heroku to death and use it for everything in development, but its costs are not conducive to growth in production
however its free tier is more than adequate for most projects while they are in development and then your entire deploy process consists of running git push heroku master rather than configuring a vps, linux, nginx, gunicorn, everything else
it's all tradeoffs depending on needs and goals and resources
the free tier didnt seem that great and i think $5 is a good price for what im getting
and i dont really have a problem setting it up
for heroku? if you had lots of usrs it would be a problem because heroku's free tier has to spin the application down when it isnt being used much, so in production it wouldnt work. but in development it works fine since presumably you arent using the app for 24 hours each day
and when i am using it with the free tier and free postgres db it can still handle a couple thousand active [simulated] users
id prefer it to be up all the time
but anyways
yeah totally, just asking. sometimes simplicity is important for people
then yeah the de facto thing to do would be ubuntu instance, nginx web server proxying to your python app which is using gunicorn
i would still perhaps recommend caddy because you can go from never having touched it to a production-ready server for your python app and automatic ssl in less than 10 lines of configuration and a few minutes
nginx is certainly the standard and is fantastic but it's much more complex
guys i am making a little CRUD twitter-like app
where can i find ideas for user account html files
this is it for now
@vagrant adder ...as in like, design inspiration? or as in you know how it should look but not sure how to implement it? if it's the latter, then you need to either take a step back and dive into html/css, or you should use a ui library (bootstrap, bulma, whatever) that already has the html/css made and you just have to put them where you want
it's just that i'm not a creative soul
yeah that's the age old question, how should it be designed? and theres ever a perfect answer
i of course make note of how things are laid out that i think are welll done
and i spend lots of time on dribbble and visiting various design inspiration lists
i thought of wix but wix is essentially markerstore template list
you thought of wix as in... you like how their user profile pages are designed? or what
wix does have some pretty well designed stuff on occasion
I have a view with an int at the end in routing, for example: ```py
@app.route('/some_view/int:id')
def some_view(id):
return f'Example result for id: {id}'
The only problem is that I would like to check in templating if the path is `/some_view/<int>` but do not know how to.
Basically what I need to do: ```py
if request.path == url_for('some_view', id=[NEED THIS]):
It will detect if the ID is anything.
The thing I am trying to achive is a navbar so I have to do it in templating FYI
Nobody? :(
@steel tiger like pagination? You can grab a bootstrap example and there are a bunch of tuts on how to set it up with flask or Django
Hello!
Can anyone tell me how to start with Django.
Im intermediate in Python.
@weak hazel I've been following this recently
Django, API, REST, Quickstart
it's been fantastic
hey @junior cloak, do you know what they mean in this pic by "app key"?
@quaint ledge where on earth are you finding these tutorials
DO
even this little snippet looks strange
but to answer your question
the secret key is just any random, hard to guess string
doesnt matter what it is, nor do you have to remmember it
just a very long intense password
it's used when flask needs to secure the cookies, sessions, etc
where do i uhh get it