#web-development
2 messages ยท Page 37 of 1
But it comes at a cost because understanding Laravel is a pain in the ass, it does soo much abstraction
Read this for a good laugh
Understanding how it works under the hood I mean **
I was ready to learn it in depth
But a friend of mine who's from the bay and worked at a couple big N's was like "Hey man, I don't see any new projects being made in PHP around me, I think you'd be better of focusing your efforts elsewhere"
So here I am ๐
Lol very true. But worst case, there are plenty of legacy systems in PHP that companies want to keep maintaining. So you'll have a job for quite some time ๐ค๐ฝ
@lone cave haha well im 21 so im not too invested, ill switch languages before getting into the legacy apps lol, not interested in that
Do you guys use pycharm or something else? Autocompletion is kinda iffy for some reason
Like the request object in flask is supposed to have a json property, but its not showing in autocomplete
I use vim
savage
If I require more I'll figure it out then but I never have
so no autocomplete, syntax highlighting ?
I found out about relative line numbers this week it changed my life lol
Syntax highlighting comes default with vim
@native tide Lol right on! You're young, make sure to enjoy your life at the same time! And yeah Pycharm, it was hard to go back to vim or anything else after that (there is a vim plugin as well).
You can use IdeaVim which is cool
I think ill try building one or two apps without connexion so I see how stuff works and then I'll build one with
have you used it @lone cave ?
@native tide Definitely, learn vanilla flask then use those extensions for bigger production apps. Yeah I used it for one project, it was nice being able to define my routes (and more) with a yaml file.
Real Python writes some amazing articles: https://realpython.com/flask-connexion-rest-api/
Anyone know why I have to do "from .." instead of just "from config"
The file that's opened is init.py
@native tide looks like config.py isn't in your system path? So python has no idea how to find it (which is why you had to use a relative import).
Can you move it into your api folder temporarily? To see if it importable. Some IDEs will automatically add your current project directory to your PYTHONPATH env variable.
Cool that did the trick
If this is Pycharm, right click on your root project folder and click Mark Directory as and choose Sources Root. Then everything will be available for import.
Looks like you're using virtualenv, I don't normally keep my projects in the same folder as the virtual env. But try using venv as the root for now.
Nice, np!
marked venv as root
Do you mean you dnt create a new venv for eaach project
Or just that you keep your project files outside of the venv folder
Ubuntu
Ah yeee
So check out https://github.com/pypa/pipenv
It's like npm for python basically. It uses virtualenv underneath. It will put all your venvs in ~/.local/share/virtualenvs I think. Then just change your interpreter in Pycharm to which ever one matches your project.
Pycharm has it all built into. So you can create envs from the IDE settings.
Am I supposed to be able to run pip from outside a virtual env ?
I just installed it in one of my venvs using pip install --user pipenv
Are you sure it wasn't activated?
Also, I believe venvs can be created to inherit the system environment's packages
Yea it was activated
Well there you go, that's why
Yeah so you can have pipenv on your host system, then use Pycharm to create venvs (using the pipenv tools that are built in), then install deps once it's activated (using pipenv preferably).
Ok yea
Now I have to add ~/.local/bin to my path yea ?
I had to install it with sudo apt install python-pip
Wouldn't that be the Python 2 package?
Lol looks good. You can check those into git as well ๐
@lone cave out of curiosity do you host your mysql-server on your host or in vagrant ?
i cant stand sqlite
Okay
Laravel used vagrant
hmm
do you use a docker file in particular ?
like a public one on github or something
There are plenty of images available on Docker Hub. You should be able to just use one of them as is, with many (or any) changes.
The PostgreSQL object-relational database system provides reliability and data integrity.
I use redis at work for some client side stuff, no modifications, just download it and run it.: https://hub.docker.com/_/redis/
Redis is an open source key-value store that functions as a data structure server.
If anything, you would write your own docker-compose file, to define and configure your services. It's really handy. One command to bring up/down the whole stack.
hey.. not a python related question but thought you guys might know.... is there a reason there is not an index.html file in my directory, and only an "html" file
@pearl iris can you send a screenshot
nevermind... just made my own file
hey this is gonna sound weird but does anyone kknow javascript
i need help with this thing i can do in python but i wanna check how to do it with js
what do you wanna know
If i push something to the database from the django admin panel i need to restart the server to see the changes
I am using Objects = Class.objects.all()
do i need to keep refreshing the objects with an asyncio loop or something ??
ping me
hey everyone! i am new to python dev + this discord (4+ years of java dev). hopefully this is the right chanel and if not is there a framework specific channel? Anway, I am using fastapi and curious if anyone has any input on how to create a session decorator that will allow each router (controller) endpoint to have a specific session. i current have this but I have to pass this down to my service and repository layer which is not ideal. i am coming from a Spring Boot background that allows me to just use @Transactional and im good to go. let me know your thoughts!
"""
Create a database session. Each incoming request will need a separate database
Session in order to preserve data integrity
Returns: database session
"""
db = None
try:
db = SessionLocal()
yield db
finally:
if db is None:
raise ResourceClosedError("No database connection.")
db.close()```
anything wrong with this piece of code?
display: grid;
grid-template-columns: repeat(2,1fr);
margin-top: 2.5px;
background: rgb(66, 65, 65);
color: rgb(255, 253, 253);
font-size: 16px;
}
#about{
display: grid;
grid-column-start: 0;
grid-column-end: 2;
}
#info{
display: grid;
}```
cuz it doesn't show as i want it to
How you want to display it @native tide
two columns on each row
but its not really working out
look how it displays
the gap between some info and all that other text doesn't show either
Let's say I havea todo app. That app has tasks with subtasks. The subtasks would be linked to the tasks via a relationship. how would I grab all the tasks of a user and then all the subtasks of that user?
It depends on the channel, the time, and the moment. A lot of us are celebrating Christmas Eve or preparing for Christmas at the moment.
yeh, unlike me cuz i don't celebrate Christmas๐
Yeah, it's different for everyone. I think a sizeable portion of our staff does.
is anyone good with 2captcha api?
if i were to have like 200+ pictures for a django project, where would the best place to store them? should i still be using a static folder for my media files still?
hi i'm looking to build a simple web server. what is the current recommendation for beginners trying to do something simple and easy.
this is for a practical 1 person project
i dont need something for a large team or anything. its just for a personal project.
@indigo parrot sure, that's fine. If it starts to become a lot and you want to offload the work of fulfilling requests for images then you can use something like amazonS3 to store your static and media files
@indigo kettle awesome - i will take a look into that
Hey I was just wondering how I would pull of this scenario in Flask SQLALCHEMY. So I have a query on a database but I want to make sure the results of that query or not ANYWHERE in another database. How would I do this?
Hello, if i change my model in django. Do I need to just migrate again to apply the changes?
make new migration and migrate again iirc
thanks!
Hi Guys,
Currently, I am building a stable back-end where I have to use social authentication. I am using django-rest-framework for building the Restful API. For implementing social authentication, I am trying to use Django REST Framework Social OAuth2 but provided documentation is not driving me properly. Need some light on it, maybe a documentation or a repository or another package with good documentation.
I've never figured out how to do OAuth, despite a few reasonably-decent stabs at it
@junior cloak Hey, I had a question about Vue and saw you talking about it after searching for it here so figured you might be the best person to ask. I'm not really sure what the best way to integrate Flask and Vue is, I know you can serve Vue's compiled index.html and then not need to run 2 servers or that you can run 2 servers and have one act as the backend API and the other the frontend but there doesn't seem to be any information about which is the better way to do it. Is there any downside from serving the compiled index.html or is there any benefits to running 2 servers?
How would you guys prefer the api
response = Response().header('application/json').status(200).create()
or response = Response(mimetype='application/json', status=200, body=...)
Perhaps just a JSONResponse(object, [..status=200])
why the square brackets around ..status ?
that's a convention from the python docs to indicate it's optional/that's the default
class Response:
def __init__(self, mimetype="text", status=200, body=""):
...
class JSONResponse(Response):
def __init__(self, obj, status=200):
super().__init__(mimetype="application/json", status=status, body=json.dumps(obj))
kind of thing is the idea
Okay I see
And the builder pattern is not needd ?
needed *
cuz I laravel i think its really nice
how you can do
return response()->withHeader('content-type', 'application/json')->json(...)
but I've been reading on the builder pattern in Python and apparently it's less needed because Python has named arguments
Hi guys
Hello, you know how you have an admin side and your index.html which is your templates views. to access it for example it's either localhost:8888/admin or localhost:8888/mysite. But what if I want to host my app on my website. is it possible to make it directly www.mywebsite.com or do i always need to do www.mywebsite.com/mysite?
yes it would be /mysite still
if you want it to be mywebsite.com, you have to play with routing of your app
Hi
Anyone know how I can change a card height in bootstrap 4?
Without changing css, only through HTML
@quartz lily https://getbootstrap.com/docs/4.0/utilities/sizing/ https://getbootstrap.com/docs/4.0/utilities/flex/
Easily make an element as wide or as tall (relative to its parent) with our width and height utilities.
Does anyone knows how to insert a node into an existing one using Jinja2?
I want to inserthtml <i class="fas fa-search"></i> inside ```python
{{ form.submit }}
@quartz lily but I don't want to assign a class to it, I want to append the node html <i class="fas fa-search"></i> to the nodepython {{ form.submit }} as a children
So I was wondering how to see if a user is not in a many to many relationship. Here is my current code:
//
seenmatch = db.relationship("User", secondary=seen, primaryjoin=(seen.c.user_id == id), secondaryjoin=(seen.c.match_id == id), backref=db.backref("seenmatches", lazy="dynamic"), lazy="dynamic")
//
users = User.query.filter_by(gender=gender).filter(or_(User.height == height, User.grade == grade)).filter(User.username != current_user.username)```**.filter(seen.c.user_id != current_user.id)**```.limit(10).all()```
The bolded section is what I am trying to work with. What I am trying to accomplish is to display 10 users or matches to the user. When the user refreshes the page, the same matches should not be seen again. To make sure the user doesn't see the other matches again, I have added a many to many relationship. The only problem is to get the filter to work to not show users that have already been seen. When I ran this code, it showed no users at all. If anyone can help me with this, it would be greatly appreciated!
Hey, does anyone know of a simple captha library which could be used in web?
Limitations:
- No 3rd party services (I'm looking at you Google), and no JavaScript requirement.
You will automatically know how to make your portfolio with django if u know django
u can google some portfolio designs online, but the backend should be very simple, frontend might be challenging
Hi guys. I am using beautifulsoup4 to get text from a website. A part of the html is as following:
<ul>
<li>Improved third person view offset so that it now positions at the average head height rather than the center of the character's capsule. This should improve how it feels when the camera is brushed up against a collision in the world.
<ul>
<li>(Can be turned off by editing your ShooterGame\Saved\Config\WindowsNoEditor\GameUserSettings.ini -> Underneath the [/Script/ShooterGame.ShooterGameUserSettings] title add the following setting: bUseOldThirdPersonCameraTrace=true)
</li>
</ul>
</li>
<li>Improved third person aim offset so that there is less likelihood of foliage clipping and allow for tighter angles when aiming down
<ul>
<li>(Can be turned off by editing your ShooterGame\Saved\Config\WindowsNoEditor\GameUserSettings.ini -> Underneath the [/Script/ShooterGame.ShooterGameUserSettings] title add the following title: bUseOldThirdPersonCameraOffset=true)
</li>
</ul>
</li>
</ul>
When I loop through the tags, getting the text, I get some parts double. Here's the code:
string = ""
for tag in html.find_all():
if tag.text is not None:
string += f"- {tag.text}\n"
The output looks like this:
As you can see, the second point is repeated in the first. I want to prevent that from happening, is there anyone who can explain me what is happening and how I could fix this up?
hi guys, i'm trying do create a django view where there is a search bar and when i search for something i want that item to be searched in google, bing etc. So i was thinking of using django, celery and redis. My question is how can i run multiple tasks using redis and how can i load the results to the page...(using ajax maybe) because i don't know then the search results will going to appear
#views.py
class SearchListView(LoginRequiredMixin, TemplateView):
template_name = 'search/seach_listView.html'
def post(self, request, *args, **kwargs):
task = adding_task.delay(2,5)
print(request.POST)
context = {}
context['GoogleSearch'] = task.get()
return JsonResponse(context)
#tasks.py
from celery import shared_task
from time import sleep
@shared_task
def adding_task(x, y):
return x + y
Hi. I'm setting up a nodejs server for a service where i want clients to be able to subscribe to updates from the server, which will occur pretty regularly every 30 seconds (or thereabouts). If anyone with some experience with this could point me in the direction of relevant documentation/examples for that i would be very grateful. I have tried to search for it, but I'm a unsure about what applies to my case.
it might not be the best place for nodejs dev, people here probably more commonly use python on the serer, and js only in the frontend
but if you want push notifications, the modern way is certainly websockets, other options include SSE (server side events, which are just a requests that never close, but it's only one direction), and the good old long polling or even repetitive polling, which is certainly the easiest but ugliest.
websockets is the way i wanted to go, thanks @simple escarp ! I knew there had to be some functionality for it, but i couldnt quite google the right terms and got stuck reading about pubsub
its annoying when you know there has to be a common way to do something, but you cant come up with the right term to get you on track
@exotic sand That's because the .text attribute contains all the other tags within that tag. If you actually want the tags own text, use .string
You may instead want to just use soup.strings, which will give you a newline-delimited list of strings in the page
hey guys, sorry for interrupt
i'm with a little issue in html
i guess it is really small problem
but i'm not finding keywords to google it
you know the input bar (insertion bar, this one flashing while we digit things in our keyboard)
how do i centralize it in css?
the field is centralized, but the bar is align left
my input location is starting here :
and i want it to be right in the midle
@wild thunder are you saying the entire text input field is in the center but its inputting text in the left?
see, there is written "Enter username or Email"
i want to my input bar
be right in the middle
and as the username or email is writen
it expands from center
make sure text-align:center is being applied to the div container for the input field. If I'm understanding you correctly that should center the text input field
lemme see
good guess, made sense
but that's not it
it "is working"
while i don't click on the field to input
almost got it, check print :
it can be straight in the middle?
ohhh okay I see now
my "input bar" is kidding me
yep, you can align that also with text-align:center. It has to be set to the actual input field, with a class or id
I can show you
but let me explain
the properties
are not being passed
to the field
my text color is not being passed too
it is suposed to be white, it's black
is it :active?
oh, now it worked (the color)
but the positioning in the input bar is not centered yet
<body>
<div class="center">
<h1>Enter your Username:</h1>
<form>
<input type="text" placeholder="Username" class="center">
</form>
</div>
</body>
<style>
.center{
text-align: center;
}
</style>
actually easier with just one class applied to both elements
so make sure you have text-align:center for both the container and the input field. I can't really help any further without seeing your code
i has not worked yet
i'll send the code
<form>
<p>Username</p>
<div id="center"><input type="text" name="" placeholder="Enter Username or Email" ></div>
<p>Password</p>
<div id="center"><input type="password" name="" placeholder="Enter your Password"></div>
<input type="submit" name="" value="Login">
<a href="#">Forgot Your Password?</a></br>
<a href="#">Create a New Account</a>
</form>
how to put inside this code box?
like this but with html instead of python
those are backticks (tilde key)
see you have center only applied to the containers
yes
should wrap the form in a <div> and have input fields as separate lines. I don't think you need separate divs for these
<div class="center">
<form>
<input class="center">
<input class="center">
</form>
</div>
should wrap the form in a <div> and have input fields as separate lines. I don't think you need separate divs for these
and the id property is only used for one specific element, you should use a class instead
it is almost solved
the information stays put in the center
but the insertion bar stills kidding
i'm really tired, it's like 2:23 here, i'm in this since 18:00
i guess i'll continue tomorrow
i'm losing my head already
and it's a personal project, not big deal
oh man that's rough, if I find something I'll put it in here
but thank you! helped a lot centering the input info already
it's just that bar
but thank you man, have a nice one
i'll come back tomorrow
good night
glad I could help. have a good one
Which option should you usually use?
does that mean if you use function as view loader then you use the first one
and if you uses class you use the second one right
So i guess everyone would use classes right
If you use classes, yeah, that's what it would indicate to me
A small doubt in flask,
Will we be needing jwt along side flask-login extension? if so when ?
When I try to create something new with django I hopon to github to see if somebody else has done it. And there it is, but it's old django, like 2 years ago, is there a way to convert old django apps to new ones or should I just try to do it myself
and they didn't include requirement.txt
Oh found it. it was Django==1.11.3
hey guys, I'm making a Restful api with Flask, but I'm not sure about the app structure, it feels like way too many files
what I'm doing is initializing my app within the __init__.py, paste and user dirs are my blueprint containers, I'm creating the blueprint in the [module]_blueprint.py, and importing all my routes and models to the __init__.py of the blueprint module, which is later imported to the app, as shown bellow
from flask import Flask, Blueprint
from flask_cors import CORS
from flask_restful import Resource, Api
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# Defines the WSGI application object
app = Flask(__name__)
# Configs
app.config.from_object('config')
# Enables CORS
CORS(app)
# Defines the database object
db = SQLAlchemy(app)
# Defines the ODM object
ma = Marshmallow(app)
# Imports blueprints
from app import paste
from app import user
# Builds the database
db.create_all()
can I structure this in a smarter way?
I just pushed it to github, so maybe you can see the files better https://github.com/d4sein/Pastebin/
if all your backend controllers are as simple as https://github.com/d4sein/Pastebin/blob/master/backend/app/paste/controllers/delete_paste_controller.py then I'd say you've pushed it a little too far
but only a little
lol, its just for testing atm
they'll be relatively big
in this mean time I made some changes, instead of using [module]_blueprint.py to create the blueprint, I initialized it in the module's __init__.py, and did the same for controllers and models, instead of using [module]_routes.py and [module]_models.py
honestly I don't know what a "blueprint" is
I'm learning so I know this is overkill for this project in specific, but I wanna get the hang of it
blueprints are just extensions of your app
web apps have this weird terminology that always makes me fidgety -- model, view, controller, &c
yeah, thats what I'm trying to learn, kek
I suspect that deep down those terms don't mean as much as they want me to think
its not really that crazy, roughly speaking it's just a way to organize your app
@frosty nymph you are doing mvc wih flask?
good luck
why?
I'm just gonna use Flask for the API, so I don't see why that wouldn't be possible
it's not impossible by any means
everything can be done with everything
but flask is meant to work like a bunch of little flasks, or so called blueprints
and each blueprint has few routers
I kinda get what you're saying, but having models and controllers within each blueprint doesnt technically make your app MVC?
see that's the thing
you don't have models in blueprints
all models are usually kept in app/models.py
and blueprints are just controllers (views too if you are building static sites)
I see
I was going for something like this
I know models are not part of the blueprint, but I'm importing them through the blueprint
i see what you are doing and i completely understand your architecture
thats the blueprint init
from flask import Blueprint
from flask_restful import Api
paste_bp = Blueprint('paste_bp', __name__, url_prefix='/paste')
paste_api = Api(paste_bp)
from app.paste import controllers, models
@vagrant adder do you think it can work?
i think it can work
cool, I'll give it a shot
but you gotta manage your imports well
yeah, this is still a work in progress
I'm trying to keep it simple, but sometimes things get a little tricky, like this from app.paste import controllers, models that has to come after the blueprint definition
yes, mvc life is tough
I appreciate the help tho
also, idk how sqlalchemy will love multiple model files
I did some tests earlier, seemed to work fine, I'll keep an eye on it
keep up the good work, really curious how it will turn out
has anyone used a mongodb with flask-admin? i keep on getting NotImplementedError
alright, I'll let you know when it's done
has anyone faced this issue: installed django 3 while using python 3.7. whenever admin page was accessed the server shuts immediately
django 2.2 works fine though
Hello, if we use the django users pre-configured. can we still use a custom model to define for exemple a user profile?
I could for example tell one of the field, that needs to reference User from auth.models?
Quick question: I have a small flask app to display the content of my database in a nice table.
Right now I'm simply sending the sqlalchemy query result to the template. I started doing server side filtering, but it's kind of a pain, and it will be even more painful and messy if I want to implement more filtering and ordering to my table.
It seems that client side (javascript) is the better way for making my table dynamic. I'm no good with javascript, my webapp don't use it much so far.
Anyway, most guides and scripts I found (like jquery, angularjs stuff) work with json data, I can't find anything that would let me manipulate my sqlalchemy data directly, but client side.
any advice?
Only python can manipulate your data directly
so javascript is not able to "read" a python sqlalchemy object?
sorry it's a bit late here, my brain might not be thinking straight haha
You are right, js can't fiddle with sqlalchemy
You could send data separately of html
Serialize sqlalchemy in json, and send it
return data_dict
It doesn't matter
You can redo your whole backend and use something like flask-restless
I don't need a rest api, really. It's just a personal database that get updated with cron jobs. Just want improve the webapp to display the data in a more practical way.
Then you'll have to serialize
RIght now I simply query.all(), send the data to jinja, with some pagination. Today I added a couple of buttons in my table to call new sqlalchemy queries (order_by...) and refresh the template. It's ok, but I feel like it's messy with the url arguments, all the if conditions, all the queries... and it's pretty limited too.
if I do serialize, I'm afraid the json file will be pretty huge, like 5Mb or something. Isn't that going to be a problem?
yes, there is around 20k rows in my db, and each rows have a bunch of relationships
I am not an expert when it comes to big numbers
Each relationship will add like 5 lines to the json, with around 200 relationship by row, time 20k rows.... well... it's too big
I'll wait to see more answer. I'm not good with web stuff and javascript, and it's too late I'm not thinking straight. Maybe I'll just do all of the filtering/ordering server side, but I will need some serious refactoring.
ty, good night
Good night sir
My flask app seems to be working, but I want to test it by having a program that creates specific jsons, sends them as requests to the app, and looks to see what the returned json is
Is that possible? I'd look it up but I'm not sure what to call sending a json programmatically.
Hello guys!
I was interested a little bit in web frameworks. I checked Spring Boot, but for some reason, even if I like working in it, I would like to work in something that I can have a job after. Of course, I am still young and everything, but I think that Django is probably capable of making web applications/sites as good as other frameworks are possible. So, I want to ask you few questions, so I can think a little bit more about learning it:
- Is it complicated/hard to setup ?
- Is it hard to access elements from HTML (since my first project will involve this, obviously) ?
- Is it complicated overall to add new pages ?
- Is it complicated to control MySQL database with it?
Thanks in advance ! ๐
@primal grove yes that is achievable
That's called mocking
Unittest and pyest achieve that quite well
Anyone used Stripe with django before?
Are there any good tutorials on making an api with Django or Flask
google is your limit
corey schafer has a tutorial how to make a static website both with django and flask
idk about apis
[flask ajax problem]
hello, i'v a problem with flask ajax post, it's have been confusing me whole day...
@app.route('/ranPic', methods=['POST'])
def ranPic():
pic = os.listdir('./static/img')
ran = random.choice(pic)
img = url_for('static', filename=f'img/{ran}')
return jsonify({'src':img})
$(document).ready(function () {
$("#nextBtn").click(function (event) {
$.ajax({
type: 'POST',
url: "/ranPic",
data: {
src: $('#img_id').attr('src'),
}
.done(function (data) {
$('#target_name').text('Changed');
$('#img_id').src = data.src;
}),
// success: function name(data) {
// $('#target_name').text('Changed');
// $('#img_id').src = data.src;
// },
error: function () {
alert('error');
}
});
event.preventDefault();
});
});
if i use .done
$('#target_name').text('Changed') will be not working
and $('#img_id').src = data.src; working but will show:
Uncaught TypeError: {(intermediate value)}.done is not a function
.done(function (data) {
$('#target_name').text('Changed');
$('#img_id').src = data.src;
}),
if i use success
$('#img_id').src = data.src; will be not working
success: function (data) {
$('#target_name').text('Changed');
$('#img_id').src = data.src;
},
have you try to console.log the data
also are you sure, that you are sending a good data to your backend @latent marsh
if the data isn't sending well. wouldnt you need to make an payload and use Json.stringify $("#nextBtn").click(function (event) { var payload = { src: $('#img_id').attr('src') } $.ajax({ type: 'POST', url: "/ranPic", data: JSON.stringify(payload) });
@native tide thx for reply.
if i use console.log it will flash out
so i use alert, and seem data is fine console.log(data.src)
still same :(
for now code is:
$("#nextBtn").click(function (event) {
var payload = {
src: $('#img_id').attr('src')
};
$.ajax({
type: 'POST',
url: "/ranPic",
data: JSON.stringify(payload)
})
.done(function name(data) {
alert(data.src)
$('#target_name').text('Changed');
$('#img_id').prop('src', data.src);
});
});
then .done
alert(data.src) work
$('#target_name').text('Changed'); not work !
$('#img_id').prop('src', data.src); work
success
alert(data.src) not work!
$('#target_name').text('Changed'); not work !
$('#img_id').prop('src', data.src); work
it's really weird....
here's full code
https://github.com/Proladon/Image_Classifier/tree/Test_Version
not yet....okay let me research for it 
So, only $('#target_name').text('Changed'); is not working, right ? What's #target_name ?
ah..... just finally success in this moment.... and i still don't know why.
guess it's the cache problem, cuz it's success after i Restart the PC
now then whenever i use .done and success all works...... god..
whaaaaat
Good old caching
CTRL-SHFT-R is your friend
also never using 301's is also your friend
Not Kidding....just restart the fking PC...then works
@native root yah i'v cleaned the web browser cache every times but not work until restart PC
gross
here's the one before im restart pc
in this <p> not change (blue text 'None' need to change to 'Change' )
same code, n now works , dumb
Where have people deployed flask apps? I tried Heroku but I didn't see an option to ssh into the location where the app would live.
If you want to run on a bare vps rather than something like heroku, there's a ยฃ100 digital ocean sign up link floating around this discord which pays for a lot of $5/mo toy servers.
The point of something like heroku is that it abstracts away the server. You describe how the app should be run and how it is wired up to any other services and then you never have to think about it because it is a managed platform.
@primal grove i developed few apps with heroku, what bothers you
@primal grove if you want to ssh into your vps type this,
heroku ps:exec -a RepoNameYouHaveOnHeroku bash
and boom, you're in
def my_portfolio(request):
user_portfolio = portfolio.objects.filter(creator_id=request.user.id)
context = {'user_portfolio', user_portfolio}
return render(request, 'portfoliopublic/user_portfolio.html', context)``` I'm trying to understand how can I retrieve for example the projects from the current user connected. Also, since I just receive a request, how can i be able to make an urls that will redirects to the good page.
path('user/<int:creator_id>/myportfolio', views.my_portfolio, name='my_portfolio')
So i have found a way but i am not sure if it's the right one
on my main views, i put the user id in a context with my other content, that way I can access the user_id in my main page and add it to a hyperlink which redirects from the page i want, is that an okay pratice?
@deft garden when I envisioned how I'd deploy my app, I assumed I'd ssh into the server, clone down my repo, make the venv, install the reqs, etc
The only part of the process that I wouldn't immediately understand is what the endpoint address would be.
@primal grove you are never given a password of your vps out of security reasons
I posted above how you could ssh into your vps without password
@primal grove youโre overthinking Heroku ๐ you donโt need to do any of those things. You just push your repo to heroku, tell it itโs python, and it does the rest. Assuming youโre using either a requirements.txt or Pipfile to manage deps, it will automatically pull your repo, install all deps, and run whatever command you tell it to start the server
deploying new versions of your app are done as simply as git push heroku master. If you ever ssh into heroku for something other than exploring, youโre doing something wrong
I see.
@fierce oriole regarding Vue... the โadvantageโ depends on your use-case. If itโs simpler for you to have one repo and server with python serving everything, thatโs fine. But separating it lets you... well, separate the projects, serve them in two different places (itโs often nice to let something catering to static site hosting deal with the frontend and have python live elsewhere), etc. You get more structure, flexibility, and performance out of separating them and hosting/serving them in a manner best/specific to each, but this assumes you... care, and need this extra boost, and know how to manage all these different pieces, etc. Nothing particularly wrong with just doing it all in one place, if/when you need to adjust you will know
@primal grove yeah thereโs nothing faster, easier, more painless than heroku, especially for dev/testing. The main โgotchaโ is just that it can get costly if you stay with them and your app is in production with tons of traffic and needing lots of resources etc
I built a flask-ask app that I anticipate would be low traffic
It's more a proof-of-concept for me to put on my github and resume
bootstrap is a hosting service?
no problem
@junior cloak Hey, thanks for the reply, I ended up just creating a docker image that includes nginx and if the URL starts with /api to redirect it to Flask otherwise serve it the static file.
that works!
I have to add dashboard for visualisation of data for a web app which backend is made from django. Can anyone suggests me a good library to use and also why ?
@primal grove can I peep
You wanted to see the source code?
Alexa: what is this little blue pill for
Yeah I need to figure out the legal implications before I launch it.
Seen @primal grove I was checking to see the template.
@west arrow what template?
Stelercus, HIPPA in the US
NVM, found the solution :P
Watch Extra Files with the Reloader
When using development mode, the reloader will trigger whenever your Python code or imported modules change. The reloader can watch additional files with the --extra-files option, or the FLASK_RUN_EXTRA_FILES environment variable. Multiple paths are separated with :, or ; on Windows.
$ flask run --extra-files file1:dirA/file2:dirB/
# or
$ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/
$ flask run
* Running on http://127.0.0.1:8000/
* Detected change in '/path/to/file1', reloading```
it's still weird that you have to explicitly spell them out
I mean sure, explicit is better than implicit, but it'd be nice to say "just reload 'em all, damn it"
Hello
I have a question about flask
how many times does the views.py file run ?
on a single execution ?
files don't "run"
I think that file will get loaded whenever the web server chooses to load it -- it might be as often as once per request, or as rarely as once per every 100 or so requests. It's a bad idea to count on this fact.
@dapper tusk bringing your flask API auth question over here to not muddy up #general. Have you found anything close to an answer? I will probably be trying this myself soon. I'm using MethodViews vs direct route decorators. I'm hoping that subclassing will be possible. Though I imagine either sessions or cookies might be required. (I'm a flask noob, so I'm likely stumbling through my approach.)
no, it was more of a random thought after I realized that just opening the API to the public would be a problem as it is pretty expensive computation-wise. If there is not a simple solution, I may just not bother though.
Ahh. Ok. Yeah, mine is kind of a similar situation. If I come across something, I'll try to remember to reach out.
@prisma tendon can you paste your original question here?
Original question was in #python-discussion: https://discordapp.com/channels/267624335836053506/267624335836053506/662320595832143880
@prisma tendon i would solve it by having it in headers
Create a decorator that checks if api key is valid
And then
@your_key_checking_decorator
@api.route("/idk")
return "idk"
And bam
Not home so i can't completely guide you
@prisma tendon
https://coderwall.com/p/4qickw/require-an-api-key-for-a-route-in-flask-using-only-a-decorator
This is exactly what i meant
Appreciate it! I'll tag @dapper tusk, since they were the OP.
Hey guys, so I've recently started the web development using django chapter in the book "python crash course".
I find everything so hard to grasp
Am I missing some basic knowledge?
Im currently just copying the commands in the terminal, I don't even know what a package is and what is a framework.
a framework is like a library -- a bunch of code you use to accomplish something. in this case, the "something" is "run a web site"
there's a technical difference between a "framework" and a "library", but it's not too important
for a beginner looking to get into web development, would you recommend Flask or Django?
so is Django a program that generates html code for you?
And where do you host the server?
Do you use an online web host service or what?
django is a web framework; it essentially provides a way (in python) for you to communicate with the user through the webpage (built in html/css) and also manage accesses to the database
it doesnt โgenerate html code for youโ and most of the time the servers are hosted through an online service
though it is possible to host your own server
django functions very similar to flask, but is built and structured for larger scale sites/projects
if youโre just starting out or if the site youre building is small, use flask; otherwise, if your site is larger and has more pieces to it, use django
@slender hamlet
django is a web framework, it contains few packages that together make a web framework
django doesn't make html code, templating engines do that
if you are feeling overwhelmed, i would suggest transitioning to flask
shoot
in flask, is it possible to use the 'redirect' , after a function call
i will list the code i am trying to use
# do something
redirect(url_for("main.NameOfRouteFunction"))
a=function()
so i call a function called 'function'
and instead of returning, i want to redirect to ANOTHER route
and load another page, consequently
is this possible ?
what does the function do
the function checks for a condition, in a try-except clause
if its an exception, of any kind, it should redirect
to a dummy page
a bit of code would be much appreciated ( also, the function() is being called from a route i.e a=function() is in a route )
@home.route("/saki")
def saki():
try:
b = int(request.arg.get("saki"))
except:
return redirect("python")
return render_template("index.html")
ok ... so its not possible to do redirects in a normal function ?
i am not sure
if i understood you correctly, you want that try except block in a separate function
yes, there was alot of other code before try-except block, which is why i made a function
that's cool to, i'll try to use your code for the time being
call that function, if your except block gets called, return None or something more appropriate
so
def tryexcept(some_num):
"""this is int casting func"""
try:
b = int(some_num)
except:
b = None
return b
@home.route("/saki")
def saki():
result = tryexcept(8)
if result is not None:
return render_template("index.html")
else:
redirect("python")
i would do this
๐
Hi, everyone!
I have a question about a function.
I wrote some code to do some function in python. Then, it is working well.
But how I can tell the bot doing "reload yourself" command if there is some exceptions or errors while running.
Is it regarding discord bot?
No, it is regarding to a telegram bot which I am doing.
Telegram?
for some reason I still recall this article https://gizmodo.com/why-you-should-stop-using-telegram-right-now-1782557415
How do I get text like this?
but have it aligned
Where there is one part on top, and something else directly below
obviously the top is like an h2 tag and the bottom a p tag
but how is it aligned like that
hi guys. sorry for interrupting, anyone can tell me how to make my page to have no scrolling?
my element is apparently fitting perfectly, but have scroll
there is any commandline in css for 0 scrolling?
it is scrolling horizontally
solved
Trying to set up flask with mod_wsgi and apache2. mod_wsgi and apache seem to be working, but I keep getting the error that flask is not found. I've run some tests and it turns out the app is being executed in a virtual enviroment, using /usr/bin/python3:
sys.prefix = '/usr'
sys.executable = '/usr/bin/python3'```My question is: how can I install flask in whatever enviroment/python installation necessary, preferably via pip?
I don't think I ever got mod_wsgi working
I've got it working before but it was messy copy and paste magic, I don't want to do that again
hey
i'm working on a project and i'm a little lost
about front end + back end integration
is it easy to do? example:
i have a login screen, after that, when i get in, i have a profile picture, name, nickname and clan
this data should be imported from a sql database
is it ok?
the site structure is ok, its working already
what lib i need to run a python code from a website?
like from that website: https://pastebin.com/raw/VZ8gTwNM
to run it on my file.py but the print("hello world") to be on website
A Python-adjacent question: how do I know if the terms of service for my web app is sufficient?
Suppose that it essentially says that I am not accountable for anything that happens related to using the app, do I have to ensure that the user is told where to read it the first time they use the app?
how do i change the logo showing when the tab of a site is open
at the top of the browser
I think you have to serve an image at the url /favicon.ico or something
google "favicon"
or ... it might be something you specify in the meta tag of your html ๐ Can't remember
<link rel="icon" type="image/png" href="${request.static_path('tinyurl:static/pawprint.png')}" /> is how I did it
mine currently has a grey earth logo and i want to change it
I have an extension that appends a p to body every time the clipboard changes.
How can I make it so when a p is appended and it goes offscreen, the window is automatically scrolled to the new p? 
I'm not too sure if this is relevant to this channel, please tell me if it's not
that sounds more like a javascript thing -- and no, I don't know how to do it
I've found a way even though it's very ugly ```js
function scrollView() {
const scrollDistance = -document.body.scrollHeight + -document.body.clientHeight + 2 * document.body.offsetHeight - document.body.scrollTop;
if (scrollDistance < LEEWAY_PIXELS) {
window.scrollTo(0, document.body.scrollHeight);
}
}```
what calls that function?
every time a new p is inserted, through a MutationObserver
also what happens if I'm carefully studying the beginning of the history, and then thoughtlessly copy something to the clipboard? Does it rescroll? That'd be annoying
we've wandered away from python, and javascript; and have now entered "usability" ๐
ideally it'd stay put. It should only scroll if the bottom of the stuff is at the bottom of the browser window
It's not really for a public website
It's a page made to take text from the clipboard and paste it to the browser
so I can lookup definitions of words through a mouse-over dictionary extension called yomichan
well it's not for the public but it's for (at least) you. You might be annoyed by that behavior. Or maybe not.
you might wind up overwriting the page with each entry, as opposed to appending each entry to the bottom. Just a thought.
otherwise you'll have a long trail of all your ... embarrassing URLs ... ๐

how is it that you have a photo of my cat
I'll be using this when I need to read something not from a browser
so the possibility really isn't there
ok, I'm sitting down.
yeah
so this code
<link rel="icon" type="image/png" href="${request.static_path('tinyurl:static/pawprint.png')}" />
is it django
no but vaguely similar -- it's pyramid with ... uh ... some templating library or other
lemme look
looks complicated
Mako
flask looks alot easier and is easier
unfortunately that's how web programming is often done
well flask is the web framework but all I showed you was a template.
so yeah i want to change the logo my website tab has
It turns out that flask is simpler than Pyramid, but I don't think you can tell that from the little snippet I pasted
and you don't have to use a templating system at all; it's just a common thing to do
saves effort in a lot of situations, but perhaps it's not worth it for yours.
if you're curious, the running code is at https://teensy.info/
should I learn flask or django?
i would suggest flask if this is your first time touching web dev
they both involve very similar concepts
but flask works on a much simpler level than django
Flask it is
what do I win?
bragging rights
fair enough
Anyone know any good hosting services that they would recommend me to for hosting my django site?
Amazon EC2
I have a t2.micro which is almost as small as they have; I think it's about $20/month
there's a "free tier" which ... I guess is free for a little while, or something
@fair wraith ^^
note: AWS pricing is basically incomprehensible; you have to hire a consultant to figure it out
Ok thanks! Also for my website. It requires redis. Is there a way to host this on AWS? Sorry I am not to familiar with it @quasi ridge
well you can do the "shade-tree mechanic" thing and run the redis instance on the same box ๐
but there's also some AWS product that is basically Redis with the usual AWS security, scalability, &c
"Elasticache" I think
or maybe it's Simple Cache Service
Ok will take a look. Because I was using django-channels and that requires redis
Thanks tho!
๐
Amazon ElastiCache for Redis is a Redis-compatible in-memory data store service that can be used as a database, cache, message broker, and queue for real-time applications. It combines the speed, simplicity, and versatility of open-source Redis with manageability, security, a...
ah thanks!
never used it, so ...
its fine. Ill research
I dunno what ASGI is, but an EC2 instance is just a computer -- anything a computer can do, it can do
oh it's like WSGI. Well @fair wraith it's just code; it'll work
@wild thunder up for what ? ๐
hey
sorry, i did not see your reply
i'm a little confuse about html + django
how to set things up,
how to make my site read information
from my pgsql database
Hi , I'm looking for some help. I'm trying to make bottle. I managed it. THe problem is when I Press the button "valider" which means "check" in french, it makes me an error. Could someone tell me what's going wrong ? thanks
The python: https://paste.pythondiscord.com/abudiwikeb.py
the html: https://paste.pythondiscord.com/yewolodeyi.py
The error: https://paste.pythondiscord.com/oxaxefiluv.py
@obtuse dagger let's look at send_static first
I think that one will work
do you see how you've got @route('/static/<filename:path>') before it?
and the function itself def send_static(filename): ?
the @route line tells bottle how to call the function: it tells it to parse a string from the URL, and assign that to filename, and pass that to the function
but with calcul_salarie, you haven't put the five variable names in the @route
Should I? Sorry I m new with "bottle" so I don't know ho to do it. My goal is to take the function "def retraite_salarie():" and put it on the web . But when I fill in the gaps , The error appears .however, In the Html, i picked the variables from python.
I'd certainly try it. Think about it: how is your code supposed to know the values of i, k, revenu_moyen, &c?
This is the problem that I'm trying to solve๐ . There aren't that much bottle tutorials on the web so... And especially with what I'm trying to do...
so again: you need to put those variable names in the @route line, the way you did for send_static
Ok thanks I'll try it . Thank you for the time that you're spending for me.
Can I add flask to my skillset as a python dev
Or is Django the ultimate py framework
Like rails for ruby
django is more for corporate jobs/projects
a big site with ton of requests, admin panel and such
and flask is for anything small and mediocre in size
flask is a good framework to know
there's some truth to that
both can be used for bith obviously
although I will point out that a well-known Internet retailer and cloud-service provider uses flask for some critical and very high-traffic web sites
the one in seattle ๐
ah, something local
(are there more than one? Amazon, duh)
d'oh
Thanks! @vagrant adder @quasi ridge
guys i'm having an "error" in my html + css
i'm using grids
grid inside grid
in the third, it is not responding
aparently the code is ok
it is default in grids?
or there is no limits to grid inside grids?
@sinful pelican hey!
what do you mean with confusing
how can i send the code with that nice formatting?
i guess the problem is in my css
using "html"
the html seems fine
with 3 `s
works with css?
Should
'''
css
#typingPlace {
grid-area: typingPlace;
background-color: white;
border: 1px solid lightgray;
width: 100%;
height: 100%;
display: inline-grid;
grid-template-areas: "ident" "type" "template";
grid-template-columns: 4% 88% 8%;
grid-template-rows: 100%;
}
#identType {
/* ร Esquerda da Barra de Input */
grid-area: ident;
background-color: cyan;
width: 100%;
height: 100%;
}
#textInput {
grid-area:type;
background-color: cyan;
width: 100%;
height: 100%;
}
#templateBox {
grid-area: template;
background-color: black;
width: 100%;
height: 100%;
}
'''
hm. something went wrong
it's not an apostrophe ๐
oh, got it
It's the one right next to 1
css
#typingPlace {
grid-area: typingPlace;
background-color: white;
border: 1px solid lightgray;
width: 100%;
height: 100%;
display: inline-grid;
grid-template-areas: "ident" "type" "template";
grid-template-columns: 4% 88% 8%;
grid-template-rows: 100%;
}
#identType {
/* ร Esquerda da Barra de Input */
grid-area: ident;
background-color: cyan;
width: 100%;
height: 100%;
}
#textInput {
grid-area:type;
background-color: cyan;
width: 100%;
height: 100%;
}
#templateBox {
grid-area: template;
background-color: black;
width: 100%;
height: 100%;
}
sorry that flood up there
are 3 columns inside the (typingPlace)
the result is this
its made up to a line "design" side to side
i tried grid-inline
flex
nothing working
Typingplace and templatebox have overlapping properties and you're seeing templatebox inherit the third grid row within typingplace
It's alright, grid was confusing for me at first too
Believe it or not it was easier for me to do it without grid areas
uh
i was really lost until understood basic grid
4 hours to make a web structure with no text, no titles, nothing, just areas
3 or 4 areas
Yeah it can be a little rough especially when you're doing SEO and scaling
Well with grid you don't have to worry about it as much until you do compatibility with mobile devices
thats ok then
Then you'll change your css scaling and such.
my platform should be used on a pc
Well remember, 60% of that market is probably going to be smartphone users too
yes, i'm thinking in a app futurely, but i'm first learning this basic
but, how can i do that?
this code i sent is the third grid,
there is a main "full body" grid, then a inside the area of the full body, i defined that code
i have to put something like :
grid-area: past-element > this-element;
?
Well sort of, you'd want to define them uniquely is all
dude
it worked
i cant believe it
css
#typingPlace {
grid-area: typingPlace;
background-color: white;
border: 1px solid lightgray;
width: 100%;
height: 100%;
display: inline-grid;
grid-template-areas: "ident" "type" "template";
grid-template-columns: 4% 88% 8%;
grid-template-rows: 100%;
}
#identType {
/* ร Esquerda da Barra de Input */
grid-area: typingPlace > ident;
background-color: black;
width: 100%;
height: 100%;
}
#textInput {
grid-area: typingPlace > type;
background-color: cyan;
width: 100%;
height: 100%;
}
#templateBox {
grid-area: typingPlace > template;
background-color: black;
width: 100%;
height: 100%;
}
There you go, you're basically defining the inheritance of the element
thanks man! saved my life
the second time it happened today
the first time i put an element that should go inside another, outside
then it worked, but this is real better
You can also just move the #'s up inside the typingplace to make it work I'm pretty sure
I've never defined inheritance the way you did ๐ฎ
me neither
i just had an idea
hahahah ๐
but thank you
this kinda created a bug on my VSCODE
i can't set colors custom anymore
I usually use Atom for web dev
!ask
Asking good questions will yield a much higher chance of a quick response:
โข Don't ask to ask your question, just go ahead and tell us your problem.
โข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โข Try to solve the problem on your own first, we're not going to write code for you.
โข Show us the code you've tried and any errors or unexpected results it's giving.
โข Be patient while we're helping you.
You can find a much more detailed explanation on our website.
I am trying to make an app (I am new to python/flask) I want to schedule a function in flask and the funciton should send a get or post request to a website and just grab the content-length of the web or js file I have built the user auth system but the problem is
Every user has their own urls which they want to monitor if the content length changes how would I implement this in flask so my code is robust and the application is reliable and fast
@quasi ridge I've searched on google about schedule task with flask and celery is it worth becuase all I want is just to send the request on the urls which the user has requested 3 times a day for 365 days or always just to monitor some files
sorry I've forgotten most of the context
are you the one who wants to start a long-running process from a web server?
[I'm just like when you call tech support -- those guys are always helping like 15 people at once, round-robin style]
I want to background that job and runs that job 3 times a day without disturbing my flask app sped-ability
can you guide on this a little please
I don't know if they have something built-in to handle long-running jobs, but it's certainly worth spending 30 minutes poking around their docs to see if they do
I can't really offer guidance because I simply never do this
no I mean
okay one more thing sir please
let say my client requirements are to visit a certain page every x min just to know the changes so is it good to do this task schedule with celery
I don't see why you'd use celery for that
You want a scheduler
like "cron" (although that's laughably old and hard to use)
there is a problem with cron
if I were writing this I guess I'd either use cron, or maybe "supervisord"
lets say I have 100 clients on my web and the job is on just to send req I can assign different job to cron it will take CPU usage too
I'm sorry but I'm having a hard time understanding you.
my english is not good
wait let me use translator
I want a task scheduler in flask to send request to certain web pages for updates is celery good with flask and redis for this job?
refer here
why do you want to use flask in the first place?
What you've described doesn't sound like a web site at all; it sounds like a program that just sits there, and does a little bit of work all by itself every three minutes, then goes back to sleep
Can I DM you?
no
@storm schooner so you want to do your task 3 times a day without fiddling with async?
take a look at APScheduler
okay let me check
@vagrant adder man you saved my life thanks
โค๏ธ
I am new to python and web dev no idea what I does most of the time
Hi,
I'm trying to implement some unittest cases and i'm having trouble wrapping my head around to test the query set
Can anyone help me get started? Thanks!
def get_queryset(self):
author = Author.objects.filter(title=self.kwargs['name']).first()
return Book.objects.filter(author=author).order_by('year') ```
that gets you a list of more books by the same author, right?
yeah and then orders them by year
waht im having trouble is just writing a test case for these 2 lines
according to pytest --cov, both lines need to be tested
well
a) I don't know how to test sqlalchemy stuff
b) that function is so simple, that as long as I saw it run correctly once, I wouldn't worry about testing it further
I can't think of any way that might break.
But I commend you for paying attention to code coverage; most people don't
ok - i have like 4 missing cases and theyre all about def get_queryset so if anyone can help point me toward the right direction then that would be perfect.
thanks i wanted to start the habit of testing of web apps from now on - a lot of ppl recommended it so im trying to make it a habit this year ^^
and they're correct, and I'm glad you're taking it seriously.
๐
huh there's no :namaste: emoji ๐ฆ
def setUp(self):
self.factory = RequestFactory()
self.book = Book()
def test_booklistview(self):
view = BookListView.as_view()
# create instance of get request
request = self.factory.get(view)
# test view() as if it was deployed on lookbooklistview
response = view(request, author=self.book.author)
self.assertEqual(response.status_code, 200)
so this clears the coverage report - I'm assuming it just wanted me to test out the class based views and not the actual individual methods themselves?
I assume "it" wanted to to simply ensure that each line of code gets run at least once by a test
yeahh that s what im assuming !
Does anyone here know how to connect my asp.net website in visual studio to SQL server? i'm desperate pls ๐ซ @ me or DM i dont always check here, thx.
@native tide for 99.99% of languages it is the same concept
get the uri of the sql server and enter it where docs say
@storm schooner ๐
@vagrant adder are u good with sql/asp net?
Looking for a learner programmer to learn with me on making a Django website. I have the fundamentals of python down, DJango wise no idea what im doing and want someone to learn / live collab with. That isn't scared to voice and screen share. Learning with someone is better than by yourself.
Django is really easy to learn, and the official doc + tutorial is easy to follow : https://docs.djangoproject.com/en/3.0/intro/tutorial01/
Hey this isnt necessarily python related but I didnt know where else to search... I want to download images from a website except for the page will only show one image at a time. all the image files are named like picture_001.jpg etc all the way to 999. is there a way I can download the entire array between 1-999 without going through 1000 pages and right click saving each one?
Can anyone help me with Css and Flexbox? display: flex; isnt working and i dont know why
do the contents have margin: auto?
This is the CSS code http://prntscr.com/qk0tqb
i just did it with margin: auto but flex isnt also working
What's your expected result ? "not working" doesn't mean much here
It shoul lool like this http://prntscr.com/qk0wso
And it loos like that http://prntscr.com/qk0wye
ohh im stupid
sorry for wasting youre time
Sometimes explaining your problem "out loud" helps you realize what's wrong
I have another question. My Code is http://prntscr.com/qk223z and so ist have to be in one line but it isnt in one line : http://prntscr.com/qk22i0 Can anybody help me?
how do i put an alt atribute when i put images like this
background: url('/static/Images/elviras_water_green0.jpg');
may i know how?
hi guys. i have no answers above (Sorry :/), i'm having a issue with my grid..
it's overlaping the left column and it's not being considered a box, i put background color and it does not change.
idk what to do anymore :C
this is the problem
Hi there, I'm trying to set up a quiz django app I found on github but I'm new to this, can anybody help?
@native tide that's a background image, and background images don't get alt text. However, you can set a title attribute on the matching element, for example, to achieve the same or a similar effect
If you're quite attached the idea of text that shows up if an image fails to load, you could style an element to be the same size as the image and beneath it, so if the image doesn't load it will show up. A particularly ambitious solution might style out a ::after element to do the work for you (but due to some... interesting behavioural differences between chrome and firefox on how ::after applies to images it's likely nontrivial)
Yeah the second option you gave me might do the trick
I can deal with z-index right?
Or nah just beneath it. Ok
any1 know how to turn a github repo into a github pages
?
i just tried and it didnt work
https://media.discordapp.net/attachments/517087158696280067/664294317950500874/unknown.png?width=1919&height=1118
Did you follow the instructions on github? Theyre very specific.
Ive been trying to understand why the thing I had working the other day is not working exactly the way i had it but couldnt remember what i did that made it that way. I was moving around divs and puttings things with different properties.
All it was...
I needed to load in bootstrap lol.
im entering in bootstrap classes and everything
and just like, "This is not working"
i need sleep
It was a simple enough set of elements that i couldnt tell it wasnt loaded
hey guys , how can I place 3 cards logo in the same place as amex svg ? https://jsfiddle.net/y0gLqonp/2/
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Is there a any good boilerplates for Django 3 that follows best practices?
(flask)Should I check email exists and password is correct, in routes.py or forms.py? In this flask tutorial https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins under "logging users in" heading, the teacher checks them in login route. It was ok, but I decided to put them in forms.py because I wanted WTForms to send error messages to the template. But now I have 3 identical database queries(one in each of validate_email, validate_password in forms, and one in routes). I tried to make: user = User.query... a class variable, but then I get "AttributeError: 'UnboundField' object has no attribute 'data'". I guess I should have just kept the email/password checks in routes, and sent error with template variables..
In routes.py
forms.py are just for injecting html code into templates
Routes.py do the logic
Thanks saki. I'm still a bit confused. Are forms for validating the data too, and is checking email exists and password is correct validating or something else? I'll take ur word for it anyway.
Nono
I won't go into much detail
But when you do {{ form.something }} in templates, templating engine replaces {{}} block of code with html <input> blah blah
And how you define your form in forms.py, tells templating engine what to replace with what
Oh right. He said we can put validation in there too, things like email = StringField("Email Address", validators=[DataRequired(), Email()]) def validate_email(self, email): user = User.query.filter_by(email=email.data.lower()).first() if user is not None: raise ValidationError("Email address already in use.")
yeah, I think. let me just check tutorial
is good if you used bootstrap for front end to style the form
I found it here: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins under "User Registration" heading.
Oh right.
Is this a question? @timber sentinel
wtforms passes errors to the form after validate_on_submit() if u have validators in the form class like that, and then u can display them easy on the page using jinja2.
@vagrant adder no, is an afirmation
I don't really like the duplicate code though(3 identical database queries). I don't think I can get rid of it another way. Thanks very much for the help.
๐
How do I use the flask url_for function in an a tag in javascript?
url_for() doesnt work in js
so what could I do then?
you'd have to expose it as an endpoint or something
and then use JS to call that endpoint
which would be pretty unusual
why do you need to do that?
currently I have an autocomplete function in javascript that uses html. There is an <a> and right now I have it to just redirect to goodle
but I want it to redirect to a function
Can you show us a bit of code
So once the user clicks on one of the a tags I want it to do a url_for( to the buy() ) because I need the name of the thing they clicked on.
my method buy buy(id) requires an id in the form of a string and will output a different url depending on the item clicked
e.g you click on apples the resulting link would be /buy/apples
I think what I'd do would be to just expose the whole lookup dict as a template variable, and like turn that into a JSON object. but it's a bit hacky. it's either that or make an endpoint that JS can call, but then you have to do a lookup every time. might be cleaner, though.
My items are already in JSON though
in a list
thats where the auto correction got it from
okay
@misty dune if you already have the items in a JSON, I suppose expanding that approach to just include the url_for for every item seems like a natural approach
just make it a dict instead of a list and use a comprehension to fill the dict values with url_for results.
used to be on pocoo, @native tide, but Pallets now runs all those projects
oh
they're both related to armin ronacher so it hasn't really changed hands, though
see http://www.pocoo.org/ for more details
probably free enough for now
Alrighty, let me get my shit together and try explain
DJANGO
https://gyazo.com/546b0487b445e4081cfc3a5d191636c3
HTML
<table class="table table-bordered table-striped mb-0">
<thead>
<tr>
<th scope="col">Quests</th>
<th scope="col">Pricing</th>
<th scope="col">Add to Total</th>
</tr>
</thead>
<tbody id='blacks'>
{% for q in quest %}
<tr>
<td>{{q.title}}</td>
<th scope="row">{{q.price}}</th>
<td> <button type="button" class="btnquest btn-primary btn-xs" id='butt'>Add</button>
</tr>
{% endfor %}
</tbody>
</table>
javascript
function add() {
var quantity_temp = document.getElementById("testLabelq").innerText;
var quantity_int = parseInt(quantity_temp, 10) + 1
document.getElementById("testLabelq").innerHTML = quantity_int.toString();
}
python
def quests(request):
quest = Quests.objects.all()
return render(request, 'main/quests.html', {'quest':quest})
What i'm trying to achieve is that when I click add in the quest services. It adds to a total label. Taking from the database within django.
I understand I may need to pass it as a json. I've looked into it. Nothing clearly explaining how it is done or accessed via JS. Or any other solution to my problem. I need ideas or how this can be achieved
Newbie btw
well, your js needs to talk to your backend in order to fetch anything from the database
Not sure I understand what you want, do you want a cart system ?
Kinda
But just updating the label
Without "Checking out"
I need to change the label dependent on what "add" button is clicked. Now I understand eaach one of those buttons should have a unique ID from the database.
When you click on add you would do an ajax request to your backend, passing the ID of the item, and your backed would answer with the price, that you would then insert in the label
yep, that's the most straight forward option.
Okay so ajax is where I wanna start looking. I was looking into JSON etc, a little into ajax.
basically JS uses ajax to make simple GET or POST requests, and you can make those to a regular django endpoint without navigating away from the page.
so you'll just call the endpoint, handle everything in Python, and reply with the data you need. simple and straight forward.
Not so simple, when self-taught of 2 months ๐
I would help you in more details but am at work right now
No worries, if anyone wants to jump on the project. Let me know, live share link available for visual studio code etc.
So can I ask a question now since experts are here @deep cave
I wanna have a API which maintains context but works on REST
Any idea how ?
I have created one approach but it is very expensive
https://codereview.stackexchange.com/questions/233463/middleware-which-lets-developer-maintain-dynamic-context
If you read this you'll get the problem
Any help would be appreciated
in a meeting atm, but I'll look in like half an hour
@deep cave
I think I understand what you're trying to do, I don't understand what you're asking for help with
how to avoid the race condition?
Yes also the race condition @deep cave
if you see the first part
I am opening a new python process for each user that comes
It's very expensive
Is there a direct approach ?
Like if 800 clients comes
there would be 800 python process running at the same time
I have tried threading and multiprocessing but it does not work
is there a better architecture to do this ?
okay. well, sorry, this is a bit above my async paygrade, threading was gonna be my suggestion.
but why don't you ask over in #async-and-concurrency
Been there done that
Without async is also fine for me
if there is a direct way
Thanks Anyways
why doesn't threading work?
Like it starts one thread
then it is not able to start another thread
anyways the benchmarking would be same I guess
many concurrent clients and many threads would cause an issue
like if there are 10000 threads active
threading doesn't really create real threads
it's more like async queuing inside a single process.
see if you can have this conversation with aeros over in #async-and-concurrency, just ping him, he's a nice dude. he's one of the cpython contributors for asyncio.
I gotta run
I think you're having this issue mostly because subprocess is the wrong tool for the job
it's by far the most heavy handed concurrency option, and not a good choice for this.
Hey, I made an API with Flask RESTful and its running on my domain http://phosphor.xyz/
Somehow the API only works on Chrome on my computer, nowhere else.
import json
from flask import Flask, make_response
from flask_restful import Resource, Api
from testing import Elo
app = Flask(__name__)
api = Api(app)
@app.route("/")
def index():
return "Hey"
@api.representation('application/json')
def output_json(data, code, headers=None):
resp = make_response(json.dumps(data), code)
resp.headers.extend(headers or {})
return resp
class HelloWorld(Resource):
def get(self, winner, loser):
u1 = Elo(winner)
u2 = Elo(loser)
w, l, wr = u1.rate_1vs1(u2)
return {'winner_elo': float(w), 'loser_elo': float(l), 'winrate': wr}
api.add_resource(HelloWorld, '/<float:winner>/<float:loser>')
if __name__ == "__main__":
app.run(port=80)
This is my little script to test my API. I cant access it through requests or Postman either.
My shitty request:
t1 = time.perf_counter()
req = requests.get('http://phosphor.xyz:80/250.0/250.0').json()
print(req)
t2 = time.perf_counter()
print("pseudo-ping: {}ms".format(round((t2-t1)*1000)))
i'm also having some pestersome flask issues. been around the web looking for different ways to make image uploading possible with flask-wtf, gotten this far:
<form style="text-align: center;" action="{{ url_for('predictor') }}" method="POST">
{{ form.hidden_tag() }}
{{ form.img }}
<br>
{{ form.submit }}
</form>
and my flask function is just
@app.route('/predict', methods=['GET', 'POST'])
def predictor():
form = ImageForm()
if form.validate_on_submit():
img = image.img_to_array(image.load_img(form.img.data, target_size=(64, 64)))
img = np.expand_dims(img, axis=0)
return jsonify({'prediction': model.predict(img)[0][0]})
return render_template('predict.html', form=form)
the POST works but it's never seen as validated, ever
i've tried the form.hidden_tag() method i've seen, i've tried the form.csrf_token method i've seen. neither trigger the validate_on_submit line
oh and this is all my ImageForm class is:
class ImageForm(FlaskForm):
img = FileField(validators=[FileRequired(), FileAllowed(['jpg', 'png'], '.jpg and .png images only')])
submit = SubmitField('Predict')
<form id="theform" method="POST" action="" enctype="multipart/form-data" style="display:none">
@trail thunder try adding the enctype attribute
you're my saviour @vagrant adder, ty
lmao
I want to build a flask service that will implement a game.
In this game, multiple users can connect (max 20), and it will go through each user to must make a choice within a certain duration (eg 30s). If a user does not make a chioce within the alotted time, the server will auto make a choice for that individual and move onto the next user.
My question is how would i go about implementing this sort of timer that counts down the duration each user has.
I was thinking of spawning a Threading.timer each time a user makes a choice where it will make a choice for the user at the end of the timer, or if the choice has been made, then canceling that timer, but i can potentially have hundreds of these timers at once as there can be hundreds of these games going on at once.
another solution i've been looking into is celery.
Any thoughts?
the real time functionality will be utilizing http://pusher.com
flask doesn't really like threading and async
it wasn't built for that
but quart does
quart is built on top of flask and supports async
it supports flask extensions since it's bult around flask
so if i use quart, spawning hundreds of timers shouldn't be an issue in essense right?
it would slow a server a bit
but apparently it will be less tricky to actually code those timers
after reading a bit, i think i may end up using celery
Hey guys im having a weird html issue
Could someone help
Im trying to copy this multi select dropdown
supposed to look like that
it uses the Select2 js plugin
I copied the code off this website which was
<div class="mb-4">
<select class="form-control" data-toggle="select" multiple>
<option>CSS</option>
<option>HTML</option>
<option>JavaScript</option>
<option>Bootstrap</option>
</select>
</div>
mine is showing up like that instead.
How hard is a live support chat to implement into a django back end ? Or doesnt it really effect it
hey i Want to make night shelter blog with web app in django any suggestions?
What's your experience with django ?
I was able to get the url_for function to work partially by just moving the script to the html file
but now I cant pass the stock_id
the stock_id passed should be equal to the javascript ${fit.name}
but I cant pass stock_id=${fit.name}
what should I do?
(Flask btw)
You cannot
While this is one file, the different pieces of code are executing on two separate environments
The jinja code executes to completion, and then the result is sent to the browser, where the javascript then runs on the output of the jinja code
The best choice here is usually to hardcode the url pattern in some way--maybe use a dummy stock id and find-replace it in the javascript
@vagrant adder doesnโt work without says canโt find variable fit
@native root how would I do that?
I was thinking of passing that invalid string to jinja