I created the following script to import files into my django models. It works fine, but only when using python 3.4.
How can I change this script to make it run on 2.7?
Thanks,
Error:
Traceback (most recent call last):
File "update_fromcsv.py", line 18, in <module>
l = list(csv.reader(open('test_data.csv', encoding='utf-8', errors='ignore')))
TypeError: 'errors' is an invalid keyword argument for this function
My import file:
import sys, os
import django
sys.path.append('/srv/apps/stashdDB/code')
os.environ['DJANGO_SETTINGS_MODULE'] = 'stashdDB.settings'
django.setup()
import stashd.models as m
import csv
l = list(csv.reader(open('test_data.csv', encoding='utf-8', errors='ignore')))
Gender_CHOICES = {
'Male': 1,
'Female': 2,
'Unisex': 3,
}
Stock_CHOICES = {
'in stock': 1,
'low stock': 2,
'out of stock': 3,
'discountinued': 4
}
for i in l[1:]:
cat = m.Category.objects.get_or_create(category_name = i[4])[0]
prod = m.Product(
name = i[0],
link = i[1],
description = i[6],
brand = i[7],
gender = Gender_CHOICES[i[8]] if i[8] in Gender_CHOICES else 3,
store = m.Store.objects.get_or_create(store_name = i[2])[0]
)
prod.save()
var = m.Variation(
product = prod,
variation = "default"
)
var.save()
img = m.Image(
variation = var,
image = i[5]
)
img.save()
size = m.Size(
variation = var
)
size.save()
price = m.Price(
variation = var,
price = float(i[3])
)
etc....
l = list(csv.reader(open('test_data.csv', 'rb')))
Related
I am trying to automate my shipping process using the Python fedex module. I am using developer test credentials. The code to create my shipment can be seen here:
import fedex
from fedex.services.ship_service import FedexProcessShipmentRequest, FedexDeleteShipmentRequest
from fedex.config import FedexConfig
CONFIG_OBJ = FedexConfig(key='******',
password= '*****',
account_number='***',
meter_number='***',
use_test_server=True)
shipment = FedexProcessShipmentRequest(CONFIG_OBJ)
shipment = FedexProcessShipmentRequest(CONFIG_OBJ)
shipment.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
shipment.RequestedShipment.ServiceType = 'FEDEX_GROUND'
shipment.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
shipment.RequestedShipment.Shipper.Contact.PersonName = 'Sender Name'
shipment.RequestedShipment.Shipper.Contact.PhoneNumber = '9012638716'
shipment.RequestedShipment.Shipper.Address.StreetLines = ['Address Line 1']
shipment.RequestedShipment.Shipper.Address.City = 'Detroit'
shipment.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'Mi'
shipment.RequestedShipment.Shipper.Address.PostalCode = '48127'
shipment.RequestedShipment.Shipper.Address.CountryCode = 'US'
shipment.RequestedShipment.Recipient.Contact.PersonName = 'Recipient Name'
shipment.RequestedShipment.Recipient.Contact.PhoneNumber = '9012637906'
shipment.RequestedShipment.Recipient.Address.StreetLines = ['Address Line 1']
shipment.RequestedShipment.Recipient.Address.City = 'Detroit'
shipment.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'Mi'
shipment.RequestedShipment.Recipient.Address.PostalCode = '48127'
shipment.RequestedShipment.Recipient.Address.CountryCode = 'US'
shipment.RequestedShipment.EdtRequestType = 'NONE'
shipment.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.AccountNumber \
= CONFIG_OBJ.account_number
shipment.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'
shipment.RequestedShipment.LabelSpecification.LabelFormatType = 'COMMON2D'
shipment.RequestedShipment.LabelSpecification.ImageType = 'PNG'
shipment.RequestedShipment.LabelSpecification.LabelStockType = 'PAPER_7X4.75'
shipment.RequestedShipment.LabelSpecification.LabelPrintingOrientation = 'BOTTOM_EDGE_OF_TEXT_FIRST'
The code executes without problem and outputs the following JSON:
(reply){
HighestSeverity = "SUCCESS"
Notifications[] =
(Notification){
Severity = "SUCCESS"
Source = "ship"
Code = "0000"
Message = "Success"
LocalizedMessage = "Success"
},
Version =
(VersionId){
ServiceId = "ship"
Major = 23
Intermediate = 0
Minor = 0
}
JobId = "aac513eb0455f072033104594"
CompletedShipmentDetail =
(CompletedShipmentDetail){
UsDomestic = True
CarrierCode = "FDXG"
MasterTrackingId =
(TrackingId){
TrackingIdType = "FEDEX"
TrackingNumber = "794608334864"
}
ServiceTypeDescription = "FXG"
ServiceDescription =
(ServiceDescription){
ServiceType = "FEDEX_GROUND"
Code = "92"
Names[] =
....
I would like to show the physical shipping label that the following subsection of the output points to:
Label =
(ShippingDocument){
Type = "OUTBOUND_LABEL"
ShippingDocumentDisposition = "RETURNED"
ImageType = "PNG"
Resolution = 200
CopiesToPrint = 1
Parts[] =
(ShippingDocumentPart){
DocumentPartSequenceNumber = 1
Image = "iVBORw0KGgoAAAANSUhEUgAABXgAAAO2AQAAAAB6QsJkAAAnSklEQVR42u2dzY8jyXXgg6ahlIDZSR11aHdqIWCva2Eus1B70oAPOvpP0Oiko2agg3o8xYpstLB1MVQ2fBJgqP4E722x25op9taueFrXcU4zZIG2aWBtM2nCYtJMZmxGZkR+MDMjMxgfmRxEorunMF3F+jXrxft+LwC6rAcYXsNreA2v4TW8htfwGt4eH9fwfk14I9jhk7Ztn/DC8CrkBcDwGnkwvIb368IbXhRvYF0W72J0WbwPfp+8Hjh5YBvvbXh1UbxOdFm8rh59tjW8hlcFr5bzFoKxdH22vQze2F744EPgIB/HyWFwFb/0kHljezxNeEP8kr7/QgWvRPmN/Z0ZWiVSEL/B25Wz3w6aN/5h3aW8L2yEVqu7i+F1H2Pe2d1lvb+PinhF/Id9/BtWebH8KuLl0g/eCMW/Cs+v4t92hTfRD9tbVytvneREx0QPxF/hg4TkW/HvUfZK4MUs+SjRv/4zFw2D14vfasI7jck8N+edAkhPRPhCjf+w5zhvMa83igA2YTmvb+W8Pvhordjf4eRFh8AOLbRJPwnLQ0CZwuv4LV38JH4xK/vRyefdbPnkYeXHngLlxectmDoF3tV7qYCjwFHD+8TBiz5F6G4Xv8eUF+uzwLcz3u0T5t3gv43FRIn+9ZYc+veGfuKm4DZEOe/DdBfzbvE/Y/k9JbzRO3z+WYyyD9zS+xsQ3uD6xeNf/+yvCG/8RivRv88srnxJLA1PC7tWfhfXL+5+/eGYHGFVvNd2d97AQbEn8zSt1w//68WLu+cfWtiY2Ik8/L0C3iOP/7BaYXv8cJPph6L+Rd8AV3cf4NdJeDcW+sW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e5zNdrMZ/uPVbMfgPaJr9KPfHK/D3bpf3jdvdm/e4D/u3zB4D0cEIfzNMTomvD/qj3cyWU0m+I/7yaqZN/gDzPs/j9F+Hc1j3jf988LJ6rNJE+/+/9ox758djwfMG8374z0ev5gcj5MvJj+cfNHMe/i7HYTXf3bcx7zTj/5Dj7yHw25yOEx2kx9Mdp+9abQX/3aIef/9eNjh9/c4n/TGu9vtJvjX5NjKO/ld/Nnr43x3mI96412vd5P1uhPvp787rnfrf57vAqu39/fL+Xw3mc8J7xeN8vtvh+uf/vx3x/l6F/Oir6LeeO/vd5P7+5h3wuT9l8P1+qe7T+/74c2fLyHcvYEwthefvtn9jy+aPu34tz+fxIbiPbg+fNkr73I02s1Go9ge38x2/2fd+ANx7LE//c83YB3+YO7bXyLYE6/cx/AaXsNreA2v4TW8htfwGl7Da3gNr+E1vIbX8Bpew2t4Da/hNbyG1/AaXsNreA2v4TW8htfwGl7Da3gNr+E1vIbX8Bpew2t4Da/hNbyG1/AaXsNreA2v4TW8htfwGl7Da3gNr+E1vIbX8Bpew2t4Da/hNbyG1/AaXsNreA2v4TW8htfwGl7Da3gNr+E1vIbX8Bpew2t4Da/hNbyG1/AaXsNreA2v4TW8hlf18/8BREqCrGpwnF0AAAAASUVORK5CYII="
},
}
However, I am unsure how to do this. Can anybody offer me any guidance?
Thank you!
I am testing some Python code to loop through resumes, open each, parse each, and create a comprehensive report based on the contents of each resume. Here is the code that I am running.
#importing all required libraries
import PyPDF2
import os
from os import listdir
from os.path import isfile, join
from io import StringIO
import pandas as pd
from collections import Counter
import en_core_web_sm
nlp = en_core_web_sm.load()
from spacy.matcher import PhraseMatcher
#Function to read resumes from the folder one by one
mypath='C:\\path_to_resumes\\' #enter your path here where you saved the resumes
onlyfiles = [os.path.join(mypath, f) for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
def pdfextract(file):
fileReader = PyPDF2.PdfFileReader(open(file,'rb'))
countpage = fileReader.getNumPages()
count = 0
text = []
while count < countpage:
pageObj = fileReader.getPage(count)
count +=1
t = pageObj.extractText()
print (t)
text.append(t)
return text
#function to read resume ends
#function that does phrase matching and builds a candidate profile
def create_profile(file):
text = pdfextract(file)
text = str(text)
text = text.replace("\\n", "")
text = text.lower()
#below is the csv where we have all the keywords, you can customize your own
keyword_dict = pd.read_csv('D:/NLP_Resume/resume/template_new.csv')
stats_words = [nlp(text) for text in keyword_dict['Statistics'].dropna(axis = 0)]
NLP_words = [nlp(text) for text in keyword_dict['NLP'].dropna(axis = 0)]
ML_words = [nlp(text) for text in keyword_dict['Machine Learning'].dropna(axis = 0)]
DL_words = [nlp(text) for text in keyword_dict['Deep Learning'].dropna(axis = 0)]
R_words = [nlp(text) for text in keyword_dict['R Language'].dropna(axis = 0)]
python_words = [nlp(text) for text in keyword_dict['Python Language'].dropna(axis = 0)]
Data_Engineering_words = [nlp(text) for text in keyword_dict['Data Engineering'].dropna(axis = 0)]
matcher = PhraseMatcher(nlp.vocab)
matcher.add('Stats', None, *stats_words)
matcher.add('NLP', None, *NLP_words)
matcher.add('ML', None, *ML_words)
matcher.add('DL', None, *DL_words)
matcher.add('R', None, *R_words)
matcher.add('Python', None, *python_words)
matcher.add('DE', None, *Data_Engineering_words)
doc = nlp(text)
d = []
matches = matcher(doc)
for match_id, start, end in matches:
rule_id = nlp.vocab.strings[match_id] # get the unicode ID, i.e. 'COLOR'
span = doc[start : end] # get the matched slice of the doc
d.append((rule_id, span.text))
keywords = "\n".join(f'{i[0]} {i[1]} ({j})' for i,j in Counter(d).items())
## convertimg string of keywords to dataframe
df = pd.read_csv(StringIO(keywords),names = ['Keywords_List'])
df1 = pd.DataFrame(df.Keywords_List.str.split(' ',1).tolist(),columns = ['Subject','Keyword'])
df2 = pd.DataFrame(df1.Keyword.str.split('(',1).tolist(),columns = ['Keyword', 'Count'])
df3 = pd.concat([df1['Subject'],df2['Keyword'], df2['Count']], axis =1)
df3['Count'] = df3['Count'].apply(lambda x: x.rstrip(")"))
base = os.path.basename(file)
filename = os.path.splitext(base)[0]
name = filename.split('_')
name2 = name[0]
name2 = name2.lower()
## converting str to dataframe
name3 = pd.read_csv(StringIO(name2),names = ['Candidate Name'])
dataf = pd.concat([name3['Candidate Name'], df3['Subject'], df3['Keyword'], df3['Count']], axis = 1)
dataf['Candidate Name'].fillna(dataf['Candidate Name'].iloc[0], inplace = True)
return(dataf)
#function ends
#code to execute/call the above functions
final_database=pd.DataFrame()
i = 0
while i < len(onlyfiles):
file = onlyfiles[i]
dat = create_profile(file)
final_database = final_database.append(dat)
i +=1
print(final_database)
#code to count words under each category and visulaize it through Matplotlib
final_database2 = final_database['Keyword'].groupby([final_database['Candidate Name'], final_database['Subject']]).count().unstack()
final_database2.reset_index(inplace = True)
final_database2.fillna(0,inplace=True)
new_data = final_database2.iloc[:,1:]
new_data.index = final_database2['Candidate Name']
#execute the below line if you want to see the candidate profile in a csv format
#sample2=new_data.to_csv('sample.csv')
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 10})
ax = new_data.plot.barh(title="Resume keywords by category", legend=False, figsize=(25,7), stacked=True)
labels = []
for j in new_data.columns:
for i in new_data.index:
label = str(j)+": " + str(new_data.loc[i][j])
labels.append(label)
patches = ax.patches
for label, rect in zip(labels, patches):
width = rect.get_width()
if width > 0:
x = rect.get_x()
y = rect.get_y()
height = rect.get_height()
ax.text(x + width/2., y + height/2., label, ha='center', va='center')
plt.show()
In the folder, I have '.doc' and '.docx' files. Everything seems to work fine, up until this point, directly below. When I get here, the code throws an error. Here is the troublesome code. The weird thing is, that it looks like some kind of PDF error, but I'm iterating only through '.doc' and '.docx' files.
final_database=pd.DataFrame()
i = 0
while i < len(onlyfiles):
file = onlyfiles[i]
dat = create_profile(file)
final_database = final_database.append(dat)
i +=1
print(final_database)
Here is the StackTrace:
Traceback (most recent call last):
File "<ipython-input-2-c63fca79d39f>", line 5, in <module>
dat = create_profile(file)
File "<ipython-input-1-cdc3bf75cd26>", line 34, in create_profile
text = pdfextract(file)
File "<ipython-input-1-cdc3bf75cd26>", line 17, in pdfextract
fileReader = PyPDF2.PdfFileReader(open(file,'rb'))
File "C:\Users\ryans\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1084, in __init__
self.read(stream)
File "C:\Users\ryans\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1696, in read
raise utils.PdfReadError("EOF marker not found")
PdfReadError: EOF marker not found
The code comes from here.
https://towardsdatascience.com/do-the-keywords-in-your-resume-aptly-represent-what-type-of-data-scientist-you-are-59134105ba0d
You are using package PyPDF2, which is used to read and manipulate pdf files. In the article from towardsdatascience that you mentioned all resumes that author was working on were in pdf format.
Maybe if your resumes are in doc/docx format you should explore python-docx library:
https://python-docx.readthedocs.io/en/latest/index.html
I have a function that is supposed to update Django objects, which each have two date fields, named "production" and "development". The function reads from a python object, containing a list of Django objects along with their new dates, as well as a single label indicating for the entire list whether the fields to be updated are "production" or "development".
For testing, I have two python objects, containing two different lists of django objects and dates, one for "production" and one for "development". When I call the function on one of these objects, no matter what, it's the list and dates in the "production" object that get updated, though whether the info goes to the "development" or "production" fields in those django objects still depends on the label of the initial python object being called on. I have no idea why this is happening.
Python class and initialization of two python objects:
import pytz
import datetime
class timess():
#Reflects update statuses for the two servers
lists = {
"none" : [],
"uploaded" : [],
}
servername = ""
def __init__(self, nonay, uplay, servertype):
self.lists["none"] = nonay
self.lists["uploaded"] = uplay
self.servername = servertype
timezone = pytz.timezone("America/Chicago")
d1 = datetime.datetime(1999, 8, 12, 12, 32, 41)
d2 = datetime.datetime(1996, 8, 12, 12, 32, 41)
d3 = datetime.datetime(2004, 8, 12, 12, 32, 41)
d1a = timezone.localize(d1)
d2a = timezone.localize(d2)
d3a = timezone.localize(d3)
p1 = datetime.datetime(1997, 8, 12, 12, 32, 41)
p2 = datetime.datetime(2002, 8, 12, 12, 32, 41)
p3 = datetime.datetime(2006, 8, 12, 12, 32, 41)
p4 = datetime.datetime(1992, 8, 12, 12, 32, 41)
p1a = timezone.localize(p1)
p2a = timezone.localize(p2)
p3a = timezone.localize(p3)
p4a = timezone.localize(p4)
dnonay = [
("mvol/0004/1905/0404", None),
("mvol/0004/1920/1111", None),
("mvol/0004/1930/0812", None),
("mvol/0004/1905/0214", None),
("mvol/0004/1930/1001", None),
("mvol/0004/1905/0917", None),
("mvol/0004/1930/0712", None),
("mvol/0004/1920/1202", None),
]
duplay = [
("mvol/0004/1905/0130", d1a),
("mvol/0004/1920/0624", d2a),
("mvol/0004/1930/0311", d3a),
]
dtimess = timess(dnonay, duplay, "development")
pnonay = [
("mvol/0004/1905/0130", None),
("mvol/0004/1920/1111", None),
("mvol/0004/1905/0214", None),
("mvol/0004/1930/0311", None),
("mvol/0004/1905/0917", None),
("mvol/0004/1930/0712", None),
("mvol/0004/1920/0624", None)
]
puplay = [
("mvol/0004/1905/0404", p1a),
("mvol/0004/1920/1202", p2a),
("mvol/0004/1930/0812", p3a),
("mvol/0004/1930/1001", p4a),
]
ptimess = timess(pnonay, puplay, "production")
Function definitions:
from listpage.timess import *
from listpage.models import *
def integratetimess(timess):
'''
Takes information in server update list and applies it
to mvolFolder objects in site. Does not work properly.
'''
if timess.servername == "development":
for line in timess.lists["uploaded"]:
target = mvolFolder.objects.get(name = line[0])
target.dev = line[1]
target.save()
if timess.servername == "production":
for line in timess.lists["uploaded"]:
target = mvolFolder.objects.get(name = line[0])
target.pro = line[1]
target.save()
def integrateot(namey, date, servertype):
'''
This function works when called on
a django mvolFolder object outside of the
timess object
'''
target = mvolFolder.objects.get(name = namey)
if(servertype == "development"):
print(namey)
print("development, initially:")
print(target.dev)
print(target.pro)
target.dev = date
print("development, after changing")
print(target.dev)
print(target.pro)
target.save()
if(servertype == "production"):
print(namey)
print("production, initially:")
print(target.dev)
print(target.pro)
target.pro = date
print("production, after changing")
print(target.dev)
print(target.pro)
target.save()
def integratetimesx(timess):
'''
However, when integrateot is called to loop on the
list in the python object, there's the same issue
as the first function
'''
for line in timess.lists["uploaded"]:
integrateot(line[0], line[1], timess.servername)
Django object model:
from django.db import models
# Create your models here.
class Folder(models.Model):
name = models.CharField(max_length = 19)
def __str__(self):
return self.name
class mvolFolder(Folder):
date = models.DateTimeField(null = True)
valid = models.NullBooleanField(null = True)
dev = models.DateTimeField(null = True)
pro = models.DateTimeField(null = True)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null = True, related_name = 'children')
Django shell input:
from listpage.models import mvolFolder
from listpage.timess import *
from listpage.convtimess import *
integratetimesx(ptimess)
integratetimesx(dtimess)
Python 3.7.0
Django 2.0.8
Windows 10 Enterprise Version 1803
I could be wrong, the question is a little vague and you never give an exact description of the problem, but it looks to me to be a python problem not a django one. The timess class has a class attribute called lists which you are treating as an instance attribute. Here's a concise description of the difference in a similar case. For a timess instance, self.list is a local reference to the class dictionary. Calling timess(...) changes the value in the class dictionary, so it's changed for all instances. I won't comment on the rest of the code, but to make this class work as (I think) you expect, try this instead:
class timess():
def __init__(self, nonay, uplay, servertype):
self.lists = {
"none" : [nonay],
"uploaded" : [uplay],
}
self.servername = servertype
I am trying to construct tvtk.RectilinearGridSource from tvtk.RectilinearGrid object in order to add it to the mayavi.engine.
I used to do this:
import mayavi.mlab as mlab
r = tvtk.RectilinearGrid()
r.point_data.scalars = data.ravel()
r.point_data.scalars.name = 'Temperature'
d = mlab.pipline.add_dataset(r)
but instead I would prefer to call it this way:
from mayavi.api import Engine
e = Engine()
e.start()
s = e.new_scene()
src = tvtk.RectilinearGridSource()
and then link src with r i.e., with my RectilinearGrid defined before.
Is there any way to do this ?
I've found an answer:
r = tvtk.RectilinearGrid()
r.point_data.scalars = data.ravel()
r.point_data.scalars.name = 'Temperature'
from mayavi.sources.vtk_data_source import VTKDataSource
src = VTKDataSource(data=r)
e.add_source(d)
I have set up my Python page like so (extract):
import evernote.edam.userstore.constants as UserStoreConstants
import evernote.edam.type.ttypes as Types
from evernote.api.client import EvernoteClient
client = EvernoteClient(token=auth_token, sandbox=False)
note_store = client.get_note_store()
The problem comes with this code:
filter = note_store.NoteFilter
filter.setOrder(NoteSortOrder.UPDATED.getValue())
I would then go onto use note_store.findNotesMetadata. However, I get the error:
AttributeError: 'module' object has no attribute 'setOrder'
What am I doing wrong? I tried to adapt from the example given here
Here is a working example:
from evernote.api.client import EvernoteClient
from evernote.edam.notestore.ttypes import NoteFilter, NotesMetadataResultSpec
from evernote.edam.type.ttypes import NoteSortOrder
auth_token = 'your-token'
client = EvernoteClient(token=auth_token)
note_store = client.get_note_store()
updated_filter = NoteFilter(order=NoteSortOrder.UPDATED)
offset = 0
max_notes = 10
result_spec = NotesMetadataResultSpec(includeTitle=True)
result_list = note_store.findNotesMetadata(auth_token, updated_filter, offset, max_notes, result_spec)
# note is an instance of NoteMetadata
# result_list is an instance of NotesMetadataList
for note in result_list.notes:
print note.title
here is my FULL working code:
import os
import sys
import hashlib
import binascii
from datetime import datetime,timedelta
import logging
# sys.path.append("lib")
# sys.path.append("libs/evernote-sdk-python3")
sys.path.append("libs/evernote-sdk-python3/lib")
from evernote import *
from evernote.api import *
from evernote.api.client import *
from evernote.edam.limits import *
from evernote.edam.type import *
from evernote.edam.type.ttypes import *
from evernote.edam.notestore import *
from evernote.edam.notestore.ttypes import *
from evernote.edam.notestore.NoteStore import *
from evernote.edam.userstore import *
from evernote.edam.userstore.constants import *
ToProcessNotebook = "toProcess"
isSandbox=True
# isChina=False
isChina=True
AuthTokenDict = {
"sandbox": {
# China, https://sandbox.evernote.com/api/DeveloperToken.action
"yinxiang": "change_to_your_token",
# International
"evernote": "",
},
"production": {
"yinxiang": "",
"evernote": "",
},
}
ServiceHost = ""
AuthToken = ""
if isChina:
if isSandbox:
AuthToken = AuthTokenDict["sandbox"]["yinxiang"]
ServiceHost = "sandbox.yinxiang.com"
else:
AuthToken = AuthTokenDict["production"]["yinxiang"]
ServiceHost = "app.yinxiang.com"
else:
if isSandbox:
AuthToken = AuthTokenDict["sandbox"]["evernote"]
ServiceHost = "sandbox.evernote.com"
else:
AuthToken = AuthTokenDict["production"]["evernote"]
ServiceHost = "app.evernote.com"
gClient = None
gUserStore = None
gNoteStore = None
def init():
global gClient, gUserStore, gNoteStore
logFilename = "EvernoteToWordpress_%s.log" % (getCurDatetimeStr())
loggingInit(logFilename)
gClient = EvernoteClient(
token=AuthToken,
# sandbox=sandbox,
# china=china,
service_host=ServiceHost
)
logging.info("gClient=%s", gClient)
gUserStore = gClient.get_user_store()
logging.info("gUserStore=%s", gUserStore)
isVersionOk = gUserStore.checkVersion(
"Evernote EDAMTest (Python)",
EDAM_VERSION_MAJOR, # UserStoreConstants.EDAM_VERSION_MAJOR,
EDAM_VERSION_MINOR, # UserStoreConstants.EDAM_VERSION_MINOR
)
logging.info("Is my Evernote API version up to date? %s", isVersionOk)
gNoteStore = gClient.get_note_store()
logging.info("gNoteStore=%s", gNoteStore)
def EvernoteToWordpress():
"""Process evernote note into wordpress"""
global gClient, gUserStore, gNoteStore
notebookList = gNoteStore.listNotebooks()
notebookListLen = len(notebookList)
logging.info("Found %s notebooks:", notebookListLen)
for curNotebook in notebookList:
logging.info("\tguid=%s,name=%s", curNotebook.guid, curNotebook.name)
if curNotebook.name == ToProcessNotebook:
processNotes(curNotebook)
break
def processNotes(curNotebook):
"""Process each note"""
logging.info("curNotebook=%s", curNotebook)
# find all notes in notebook
searchOffset = 0
searchPageSize = 100
searchFilter = NoteStore.NoteFilter()
searchFilter.order = NoteSortOrder.UPDATED
searchFilter.ascending = False
searchFilter.notebookGuid = curNotebook.guid
logging.info("searchFilter=%s", searchFilter)
resultSpec = NotesMetadataResultSpec()
resultSpec.includeTitle = True
resultSpec.includeContentLength = True
resultSpec.includeCreated = True
resultSpec.includeUpdated = True
resultSpec.includeDeleted = True
resultSpec.includeNotebookGuid = True
resultSpec.includeTagGuids = True
resultSpec.includeAttributes = True
resultSpec.includeLargestResourceMime = True
resultSpec.includeLargestResourceSize = True
logging.info("resultSpec=%s", resultSpec)
# foundNoteResult = gNoteStore.findNotesMetadata(
# authenticationToken=AuthToken,
# filter=searchFilter,
# offset=searchOffset,
# maxNotes=pageSize,
# resultSpec=resultSpec
# )
foundNoteResult = gNoteStore.findNotesMetadata(AuthToken, searchFilter, searchOffset, searchPageSize, resultSpec)
logging.info("foundNoteResult=%s", foundNoteResult)
if __name__ == "__main__":
init()
EvernoteToWordpress()
Note: evernote sdk is download from Evernote SDK for Python 3
Latest code: crifanEvernote.py