CustomDataLoading

Goals

Code

anki_xmlrpc_server.py

#
# FILE:   anki_xmlrpc_server.py
# DATE:   20071027
# AUTHOR: flight16@users.sourceforge.net
# DESC:   - Starts an xml-rpc server that provides an interface to add facts to
#         an Anki file.
#         - Could easily be modified to import into Anki from other data sources
#         - I have plans to expand this to provide more functionality and real
#         error checking.  Please let mme know if you find this example useful.
#

import os
import sys

### EDIT: 
sys.path.append('somewhere_on_your_computer/anki-0.3.6/libanki')

import anki
from anki import stdmodels
from anki.errors import *
from anki.facts import *
from anki.models import *
from anki.fields import *
from SimpleXMLRPCServer import SimpleXMLRPCServer

global deck, ds

### EDIT THESE VARIABLES
server = 'localhost'
server_port = 8006
anki_file = 'some_anki_file.anki'


# Initialize Anki.
ds = anki.Controller.DeckStorage()
deck = ds.fromFile(unicode(anki_file))
facts = deck.facts

# Create XML-RPC Server
server = SimpleXMLRPCServer((server, server_port))
server.register_introspection_functions()

# add_fact(struct)
#
# Add a fact to the deck.  Expects a structure with the format...
# model: <name of model to use>
# fields:
#    <field_name1>: <field_value1>
#    <field_name2>: <field_value2>
#    ...
#
# TODO: Error checking, and throw faults with useful error messages (eg. 
# 'you forgot to specify a model string'.
#
def add_fact(struct):
        values_for = struct['fields']
        model_name = struct['model']
        
        model = facts.models.byName(model_name)
        fact = Fact()

        for field in values_for.keys():
                fact[field] = values_for[field]
        
        facts.models.setModel(model)
        # Add a fact to the model we just set above.
        deck.addFact(fact)      

        return 1
server.register_function(add_fact, "facts.add")

# Saves the current changes.
def save_deck():
        ds.save(deck)
        return 1
server.register_function(save_deck, 'deck.save')

# Run the server's main loop
server.serve_forever()

anki_xmlrpc_client.py

#
# FILE:   anki_xmlrpc_client.py
# DATE:   20071027
# AUTHOR: flight16@users.sourceforge.net
# DESC:   - For use with anki_xmlrpc_server.py
#         - This could just as easily be done in Perl, Ruby, JavaScript,
#         AppleScript, Java, C++, ...you get the idea.
#

import os
import sys
import xmlrpclib

### EDIT
server_url = 'http://localhost:8006'

# 1. Connect to the server.
server = xmlrpclib.Server(server_url);

# 2. Add a fact.
### EDIT model and field names to suit your file.
server.facts.add({'model': 'Words', 'fields': {'Word': 'スイカ', 'Reading': 'すいか', 'Meaning': 'watermelon'}})

# 3. Save the deck.
server.deck.save()

Change Log

CustomDataLoading (last edited 2008-06-09 13:45:20 by )