Script to add bookmarks to a PDF (Need review and suggestions)
Hello guys,
So i made this little script that adds bookmarks to PDFs using Py2PDF module. It's not really a full automation of the process of adding bookmarks since you still have to manually add the parent bookmark and add the bookmarks (Chapters + their respectives pages) into a dictionnary. Once the dictionnary is made, the bookmarks are added with a for loop that uses the addBookmark method in a new output PDF file.
from PyPDF2 import PdfFileWriter, PdfFileReader
pdf_object = open("pdf_without_bookmarks.pdf","rb") #rb stands for read binary
output = PdfFileWriter()
input = PdfFileReader(pdf_object)
input_numpages = input.getNumPages()
#basically just copy the input file
for i in range(input_numpages):
output.addPage(input.getPage(i)) #insert page in the output file
parent_1 = output.addBookmark('Parent 2', page of parent 2) # add parent bookmark
bookmarks_dic_1 = {
"Chapter 1": page of Chapter 1,
"Chapter 2": page of Chapter 2,
"Chapter n": page of Chapter n,
}
for k, v in bookmarks_dic_1.items():
output.addBookmark(k ,v +1,parent_1 ) #add child bookmarks
parent_2 = output.addBookmark('Parent 2', page of parent 2)
bookmarks_dic_2 = {
"Chapter 1": page of Chapter 1,
"Chapter 2": page of Chapter 2,
"Chapter n": page of Chapter n,
}
for k, v in bookmarks_dic_2.items():
output.addBookmark(k ,v +1,parent_2 ) #add child bookmarks
outputstream = open('pdf_with_bookmarks.pdf','wb') #creating result
output.write(outputstream) #writing to result pdf
outputstream.close() #closing result
Initially, when i started working on this, i wanted to scrape Chapter and Page information from PDF filesummary, but i realized it was too ambitious and that it requires to know how to use regex (Am i right?).
I also want to know if there's a way to put all this in one loop, instead of having to create a new loop for each parent. But i don't know how. Like is there such thing as a dictionnary with more than 1 value? The Parent will be the key and the values Name of chapter and Page of chapter. A kind of a double dictionnary. Something like this :
summary_dictionnary = {"Parent 1":{"Chapter 1": Page, "Chapter n": Page}, "Parent n": {"Chapter 1": Page,"Chapter n":Page}}
Is that even possible?
I'm also posting here to have a general review on my code, what do you guys would change?
Big thanks in advance
/r/Python
https://redd.it/7tih40
Hello guys,
So i made this little script that adds bookmarks to PDFs using Py2PDF module. It's not really a full automation of the process of adding bookmarks since you still have to manually add the parent bookmark and add the bookmarks (Chapters + their respectives pages) into a dictionnary. Once the dictionnary is made, the bookmarks are added with a for loop that uses the addBookmark method in a new output PDF file.
from PyPDF2 import PdfFileWriter, PdfFileReader
pdf_object = open("pdf_without_bookmarks.pdf","rb") #rb stands for read binary
output = PdfFileWriter()
input = PdfFileReader(pdf_object)
input_numpages = input.getNumPages()
#basically just copy the input file
for i in range(input_numpages):
output.addPage(input.getPage(i)) #insert page in the output file
parent_1 = output.addBookmark('Parent 2', page of parent 2) # add parent bookmark
bookmarks_dic_1 = {
"Chapter 1": page of Chapter 1,
"Chapter 2": page of Chapter 2,
"Chapter n": page of Chapter n,
}
for k, v in bookmarks_dic_1.items():
output.addBookmark(k ,v +1,parent_1 ) #add child bookmarks
parent_2 = output.addBookmark('Parent 2', page of parent 2)
bookmarks_dic_2 = {
"Chapter 1": page of Chapter 1,
"Chapter 2": page of Chapter 2,
"Chapter n": page of Chapter n,
}
for k, v in bookmarks_dic_2.items():
output.addBookmark(k ,v +1,parent_2 ) #add child bookmarks
outputstream = open('pdf_with_bookmarks.pdf','wb') #creating result
output.write(outputstream) #writing to result pdf
outputstream.close() #closing result
Initially, when i started working on this, i wanted to scrape Chapter and Page information from PDF filesummary, but i realized it was too ambitious and that it requires to know how to use regex (Am i right?).
I also want to know if there's a way to put all this in one loop, instead of having to create a new loop for each parent. But i don't know how. Like is there such thing as a dictionnary with more than 1 value? The Parent will be the key and the values Name of chapter and Page of chapter. A kind of a double dictionnary. Something like this :
summary_dictionnary = {"Parent 1":{"Chapter 1": Page, "Chapter n": Page}, "Parent n": {"Chapter 1": Page,"Chapter n":Page}}
Is that even possible?
I'm also posting here to have a general review on my code, what do you guys would change?
Big thanks in advance
/r/Python
https://redd.it/7tih40
reddit
Script to add bookmarks to a PDF (Need review and... • r/Python
Hello guys, So i made this little script that adds bookmarks to PDFs using Py2PDF module. It's not really a full automation of the process of...
Simple syntax question- how to drop one table in SQL Alchemy / Flask?
The Flask documentation seems to only discuss how to drop ALL the tables:
https://flask-sqlalchemy.palletsprojects.com/en/2.x/binds/#creating-and-dropping-tables
I don't know how to interpret this, https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.Table.drop. I'm not sure if it would apply to working in Flask.
All the online answers regarding deleting one table in SQL Alchemy discuss it as engine, not, as one stackoverflow user says, a "Flask-SQLAlchemy extension object".
I need to drop a table every time the app runs because the app automatically populates this table with data. If it tries to populate a populated table, it will get a "UNIQUE" error.
On my init.py I have:
~~~
from flasksite.models import Styletable
db = SQLAlchemy(app)
db.dropall()
db.createall()
Styletable.createtable()
~~~
This works great to populate the data. But, it drops all the data from all the tables. That's not good.
I wish I could just do something like
db.drop(Styletable)
or
db.Styletable.drop()
on my models.py I have:
~~~~
class Styletable(db.Model):
id = db.Column(db.Integer, primarykey=True)
stylename = db.Column(db.String(100), primarykey=True, nullable= False)
def createtable():
a = Styletable()
b = Styletable()
c = Styletable()
a.stylename = "essay"
/r/flask
https://redd.it/pqmj4g
The Flask documentation seems to only discuss how to drop ALL the tables:
https://flask-sqlalchemy.palletsprojects.com/en/2.x/binds/#creating-and-dropping-tables
I don't know how to interpret this, https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.Table.drop. I'm not sure if it would apply to working in Flask.
All the online answers regarding deleting one table in SQL Alchemy discuss it as engine, not, as one stackoverflow user says, a "Flask-SQLAlchemy extension object".
I need to drop a table every time the app runs because the app automatically populates this table with data. If it tries to populate a populated table, it will get a "UNIQUE" error.
On my init.py I have:
~~~
from flasksite.models import Styletable
db = SQLAlchemy(app)
db.dropall()
db.createall()
Styletable.createtable()
~~~
This works great to populate the data. But, it drops all the data from all the tables. That's not good.
I wish I could just do something like
db.drop(Styletable)
or
db.Styletable.drop()
on my models.py I have:
~~~~
class Styletable(db.Model):
id = db.Column(db.Integer, primarykey=True)
stylename = db.Column(db.String(100), primarykey=True, nullable= False)
def createtable():
a = Styletable()
b = Styletable()
c = Styletable()
a.stylename = "essay"
/r/flask
https://redd.it/pqmj4g
My beginning attempt at networking device backups
This is my beginning attempt at making a networking device backup script. This script uses netmiko for communicating with the devices. I would love feed back.
Edit: Here is a link to the code in better formatting https://pastebin.com/V1tG8hCM
from netmiko import ConnectHandler
from datetime import datetime
from secrects import switchuser, switchpassword
import os
import json
devicelist = '/home/vetadmin/scripts/switch.json'
#skippagedisplay = "skip-page-display"
#pagedisplay = "page-display"
showrun = "show run"
#showhostname = "show run | inc hostname"
date = datetime.now().strftime("%Y%m%d")
s = 0
d = 0
#Creating the log file
logpath = ("/home/vetadmin/scripts/logging/")
if not os.path.exists(logpath):
os.makedirs(logpath)
l= open ("/home/vetadmin/scripts/logging/switchbackup.log", "a")
l.write("\n" + date + "\n")
#Opening the switch.json file that has all the switch ip information
with open(devicelist)
/r/Python
https://redd.it/q3xbsn
This is my beginning attempt at making a networking device backup script. This script uses netmiko for communicating with the devices. I would love feed back.
Edit: Here is a link to the code in better formatting https://pastebin.com/V1tG8hCM
from netmiko import ConnectHandler
from datetime import datetime
from secrects import switchuser, switchpassword
import os
import json
devicelist = '/home/vetadmin/scripts/switch.json'
#skippagedisplay = "skip-page-display"
#pagedisplay = "page-display"
showrun = "show run"
#showhostname = "show run | inc hostname"
date = datetime.now().strftime("%Y%m%d")
s = 0
d = 0
#Creating the log file
logpath = ("/home/vetadmin/scripts/logging/")
if not os.path.exists(logpath):
os.makedirs(logpath)
l= open ("/home/vetadmin/scripts/logging/switchbackup.log", "a")
l.write("\n" + date + "\n")
#Opening the switch.json file that has all the switch ip information
with open(devicelist)
/r/Python
https://redd.it/q3xbsn
Pastebin
from netmiko import ConnectHandlerfrom datetime import datetimefrom secrects - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How to Create An Twitterbot with simpletwitter
Github Repository: [https://github.com/pravee42/simpletwitter](https://github.com/pravee42/simpletwitter)
```
from simpletwitter import SimpleTwitter
email = "Twitter_User_Email_Address"
password = "Twitter_Password"
user_name = "Abipravi1"
#here i have entered my twitter username but you need to enter your's in this case
no_of_tweets = 10 #this value is necessary how many no of tweets you want to perform operation
bot = SimpleTwitter(email, password, no_of_tweets, user_name)
#Creating Instance
hashtags = ['#abipravi', #pythonmodule', '#twitter_bot']
tweetmessage = "My first tweet by simple twitter"
bot.login() # to login into the account
bot.like_tweet(hashtags) # like the tweet
bot.unlike_liked_tweets(5) # unlike the liked tweet
bot.tweet(tweetmessage) # put some tweet
/r/Python
https://redd.it/r7mtzy
Github Repository: [https://github.com/pravee42/simpletwitter](https://github.com/pravee42/simpletwitter)
```
from simpletwitter import SimpleTwitter
email = "Twitter_User_Email_Address"
password = "Twitter_Password"
user_name = "Abipravi1"
#here i have entered my twitter username but you need to enter your's in this case
no_of_tweets = 10 #this value is necessary how many no of tweets you want to perform operation
bot = SimpleTwitter(email, password, no_of_tweets, user_name)
#Creating Instance
hashtags = ['#abipravi', #pythonmodule', '#twitter_bot']
tweetmessage = "My first tweet by simple twitter"
bot.login() # to login into the account
bot.like_tweet(hashtags) # like the tweet
bot.unlike_liked_tweets(5) # unlike the liked tweet
bot.tweet(tweetmessage) # put some tweet
/r/Python
https://redd.it/r7mtzy
GitHub
GitHub - pravee42/simpletwitter: Twitter bot module with few lines of code
Twitter bot module with few lines of code. Contribute to pravee42/simpletwitter development by creating an account on GitHub.
How do I create multiple temporary image files and serve them?
I want to serve images on my server with the user's username watermarked on them.
So, the path I have decided to take (recommend me a better one) is creating a temporary file, watermarking the original image in the backend, saving that and then linking to the temp file.
​
This is what I am trying:
​
if file.extension() in '.jpeg', '.jpg', '.png','.JPEG', '.JPG', '.PNG':
print(file.file.url)
img = Image.open(file.file.path)
draw = ImageDraw.Draw(img)
#Creating text and font object
text = "tenth
/r/djangolearning
https://redd.it/skeu09
I want to serve images on my server with the user's username watermarked on them.
So, the path I have decided to take (recommend me a better one) is creating a temporary file, watermarking the original image in the backend, saving that and then linking to the temp file.
​
This is what I am trying:
​
if file.extension() in '.jpeg', '.jpg', '.png','.JPEG', '.JPG', '.PNG':
print(file.file.url)
img = Image.open(file.file.path)
draw = ImageDraw.Draw(img)
#Creating text and font object
text = "tenth
/r/djangolearning
https://redd.it/skeu09
Reddit
From the djangolearning community on Reddit
Explore this post and more from the djangolearning community
Arguments against separating
The Python Packaging Authority recommends separating the test directory from the src (source code) directory in a Python application:
https://packaging.python.org/en/latest/tutorials/packaging-projects/#creating-the-package-files
Personally, I have always preferred this approach of keeping tests outside the package rather than mixing them with the source code (tests in package).
However, in the interest of expanding my perspective and learning something new, I am open to exploring alternative viewpoints. What are the main arguments for including tests within the package itself?
Image taken from https:\/\/blog.ionelmc.ro\/2014\/05\/25\/python-packaging\/
/r/Python
https://redd.it/11zjjzy
test from src in a python package?The Python Packaging Authority recommends separating the test directory from the src (source code) directory in a Python application:
https://packaging.python.org/en/latest/tutorials/packaging-projects/#creating-the-package-files
Personally, I have always preferred this approach of keeping tests outside the package rather than mixing them with the source code (tests in package).
However, in the interest of expanding my perspective and learning something new, I am open to exploring alternative viewpoints. What are the main arguments for including tests within the package itself?
Image taken from https:\/\/blog.ionelmc.ro\/2014\/05\/25\/python-packaging\/
/r/Python
https://redd.it/11zjjzy
Have started the django doc again, and got stuck.
At this part of "Writing your first app", I try to type in "py manage.py startapp polls" and it shows "ModuleNotFoundError: No module named 'polls". Why is that?
/r/djangolearning
https://redd.it/1grq58d
At this part of "Writing your first app", I try to type in "py manage.py startapp polls" and it shows "ModuleNotFoundError: No module named 'polls". Why is that?
/r/djangolearning
https://redd.it/1grq58d
Django Project
Writing your first Django app, part 1 | Django documentation
The web framework for perfectionists with deadlines.